Daniel Klöck
Daniel Klöck

Reputation: 21137

UICollectionView.dequeueReusableCell crashes

In viewDidLoad I register the cell like this:

let cellIdentifier = "Cell"

override func viewDidLoad() {
    super.viewDidLoad()

    let cellNib = UINib(nibName: "ViewCell", bundle: nil)
    collection.register(cellNib, forCellWithReuseIdentifier: cellIdentifier)
}

and in cellForItemAt of the UICollectionViewDataSource I do:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // It crashes while trying to dequeue with the Error message:  Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:]
    let dequedCell = collection.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
    return dequedCell
}

The onlystrange thing might be that the code is Mixed Swift/ObjC, and ViewCell is ObjC and gets imported in the bridging header:

#import "ViewCell.h"

I am getting the following error:

*** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewC‌​ategory:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UI‌​Kit-3600.7.47/UIColl‌​ectionView.m:5106

I made sure all names are correct. Does anyone know why this crash is happening??

Upvotes: 2

Views: 3521

Answers (3)

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16416

Here is problem

1) You need to register cell identifier in XIB,

2) Assign Class name to XIB

3) cell for row you need to check with as? YourClass in dequeue and

4) dequeue with same identifier you assign to XIB and register

Upvotes: 1

Caleb
Caleb

Reputation: 124997

Does anyone know why this crash is happening?

One thing to consider is that the docs for register(_:forCellWithReuseIdentifier:) say:

The nib file must contain only one top-level object and that object must be of the type UICollectionViewCell.

So, check that that's true. In other words...

let nibObjects = cellNib.instantiate(withOwner: nib, options: nil)
let count = nibObjects.count  // is this 1?
let view = nibObjects.first   // is view a UICollectionViewCell?

Upvotes: 0

Keyur Hirani
Keyur Hirani

Reputation: 1607

Set collectionview cell identifier as Cell in storyboard.

enter image description here

Upvotes: 1

Related Questions