Swift - could not dequeue a view of kind: UICollectionElementKindCell with identifier

孤街浪徒 提交于 2019-12-19 05:31:16

问题


I got this error message when trying to load UICollectionView.

2015-07-23 16:16:09.754 XXXXX[24780:465607] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier CollectionViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

First throw call stack:

My code

@IBOutlet var collectionView: UICollectionView!

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell

        cell.backgroundColor = UIColor.blackColor()
        cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
        cell.imageView?.image = UIImage(named: "category")

        return cell

    }

I already declared CollectionViewCell in storyboard inspector but the error message still occur.


回答1:


After taking a look at your exception:

2015-07-23 16:16:09.754 XXXXX[24780:465607] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier CollectionViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard' * First throw call stack:

last part is most important:

must register a nib or a class for the identifier or connect a prototype cell in a storyboard

Which means that your collection view doesn't have registered your custom cell. To resolve this add following in your viewDidLoad:

var nib = UINib(nibName: "UICollectionElementKindCell", bundle:nil)
self.collectionView.registerNib(nib, forCellReuseIdentifier: "CollectionViewCell")



回答2:


For Swift 3:

collectionView.register(YourCustomCellClass.self, forCellWithReuseIdentifier: "cell")



回答3:


In your viewDidLoad() put in this code

collectionView.registerClass(YourCustomCellClass.self, forCellWithReuseIdentifier: "cell")


来源:https://stackoverflow.com/questions/31581903/swift-could-not-dequeue-a-view-of-kind-uicollectionelementkindcell-with-ident

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!