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

17,146

Solution 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")

Solution 2

For Swift 3:

collectionView.register(YourCustomCellClass.self, forCellWithReuseIdentifier: "cell")
Share:
17,146
Nurdin
Author by

Nurdin

My Profile - http://www.revivalx.com Data Consultant at Deepagi - https://deepagi.com KLSE & Crypto screener - https://deepagiscreener.com Github - https://github.com/datomnurdin Linkedin - http://www.linkedin.com/pub/mohammad-nurdin/57/290/692 Youtube - https://www.youtube.com/channel/UCP2lj6CO3Grss4v2ebJ1C1A #SOreadytohelp

Updated on June 25, 2022

Comments

  • Nurdin
    Nurdin about 2 years

    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.

    enter image description here

  • Paul Lehn
    Paul Lehn over 8 years
    Thank you. my problem was that I was not registering my Nib and instead registering the class with: self.collectionView!.registerClass(customCollectionCell.self‌​, forCellWithReuseIdentifier: "Cell") Your code works however.