迅捷,如何使用UICollectionView

时间:2018-08-13 04:40:03

标签: ios swift uicollectionview

我写了以下代码:

class HomeViewController: UIViewController {

    @IBOutlet var collectionView: CatagoryCollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.


        collectionView.register(UINib(nibName: "HomeCardCell",bundle: Bundle.main), forCellWithReuseIdentifier: "HomeCardCell")
    }

}

class CatagoryCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCardCell", for: indexPath) as! HomeCardCell
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    }

}

我在日志中有此错误:

  

2018-08-13 12:14:07.706452 + 0900 xxxxx [6804:3378858]   -[ID301Project.HomeViewController collectionView:numberOfItemsInSection:]:无法识别的选择器发送到   实例0x1065092b0 2018-08-13 12:14:07.707910 + 0900   xxxxx [6804:3378858] ***由于未捕获的异常而终止应用程序   “ NSInvalidArgumentException”,原因:“-[xxxxx.HomeViewController   collectionView:numberOfItemsInSection:]:无法识别的选择器发送到   实例0x1065092b0'

collectionView

我想将UICollectionView扩展到类。 您不能像这样扩展它吗?

2 个答案:

答案 0 :(得分:-1)

在ViewDidLoad()方法中编写以下行

collectionView.delegate = self
collectionView.datasource = self

之后,使用UICollectionViewDelegate和UICollectionViewData Source继承您的View Controller类

答案 1 :(得分:-1)

将您的CellReuseIdentifier字符串添加到集合单元格(蓝色矩形)。请参考下图

enter image description here