即使我为UICollectionViewDataSource添加了方法,它也给了我一个错误

时间:2017-03-25 17:27:32

标签: swift uicollectionview

    //
    //  ViewController.swift
    //  CollectionViewTry 
    //
   //  Created by Shivam Agrawal on 25/03/17.
//  Copyright © 2017 Shivam Agrawal. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout,UICollectionViewDataSource {
    var collectionView: UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 90, height: 120)

        collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        collectionView.backgroundColor = UIColor.white
        self.view.addSubview(collectionView)






        /*   print(BigBox.count)
         for i in 0...80{
         print("\(BigBox[i].identifier) \(BigBox[i].ColID) \(BigBox[i].RowID) \(BigBox[i].SmallBox) \(BigBox[i].sbCount)")
         }*/
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 14
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath)
    cell.backgroundColor = UIColor.orange
    return cell
}

ios 8.1: Type 'ViewController' does not conform to protocol 'UICollectionViewDataSource'

我的问题与上述类似。我尝试用Google搜索但无法找到如何修复代码中的错误。即使我添加了方法,但它表示不符合协议

2 个答案:

答案 0 :(得分:1)

这些功能在你的课堂之外。因此,他们不是所述类的方法。把它们移到里面。

答案 1 :(得分:0)

两个问题:

  • 对于Swift 3,数据源方法的两个签名都是错误的。正确的签名是:

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
  • 正如Roope的回答中所提到的,数据源方法必须内部。