Asbis
Asbis

Reputation: 532

How to connect custom collectionviewCell to reuseidentifier with XIB - Swift

I am making a custom collectionview cell Using XIB.

The collectionview is placed inside an viewController as an extension.

This is the code i am using to call the Xib View but i get an error telling me i need to use reuseidentifier. But i have no clue how to use that while using XIB.

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

        let cell = Bundle.main.loadNibNamed("CustomCell", owner: self, options: nil)?.first as! CustomCell

        return cell
    }

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'the cell returned from -collectionView:cellForItemAtIndexPath: does not have a reuseIdentifier - cells must be retrieved by calling -dequeueReusableCellWithReuseIdentifier:forIndexPath:' *** First throw call stack:

Upvotes: 1

Views: 1010

Answers (3)

Jamil Hasnine Tamim
Jamil Hasnine Tamim

Reputation: 4448

For Swift 4.0 and 4.2

In your viewDidLoad:

custom collectionViewCell

mainCollectionView.register(UINib(nibName: "your_custom_cell_name", bundle: nil), forCellWithReuseIdentifier: "your_custom_cell_identifier")

In cellForItemAt indexPath:

let cell : <your_custom_cell_name> = mainCollectionView.dequeueReusableCell(withReuseIdentifier: "your_custom_cell_identifier", for: indexPath) as! <your_custom_cell_name>

And don't forget to set identifier for your custom cell in xib section.

Upvotes: 1

Bappaditya
Bappaditya

Reputation: 9652

You can register the CustomCell like,

let customCellNib = UINib(nibName: "CustomCell", bundle: .main)
collectionView.register(customCellNib, forCellWithReuseIdentifier: "CustomCell")

And use the same registered cell in cellForItemAt like,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"CustomCell", for: indexPath) as? CustomCell else {
        return UICollectionViewCell()
    }
    return cell
}

Upvotes: 2

emrepun
emrepun

Reputation: 2666

First you need to create a reuseIdentifier for your cell. Lets create it based on your collectionViewCell class name. Declare reuseId, in your ViewController file:

let reuseId = String(describing: CustomCell.self)

You need to register your cell to your collectionView in viewDidLoad method.

collectionView.register(CustomCell.self, forCellReuseIdentifier: reuseId)

Then in your cellForItemAt method:

guard let cell = collectionView.dequeueReusableCell(withIdentifier: reuseId, for: indexPath) as? CustomCell else { return UICollectionViewCell() }
//return cell, or update cell elements first.

Upvotes: 2

Related Questions