coderLIfe coderLIfe - 1 month ago 9
Swift Question

How can I load multiple nib files in one CollectionView?

This only loads

DescriptionImageSliderCollectionViewCell
. I pretty sure what is going on here, but I want to load both but I don't know how to do so.

My code to register collection view cell:

override func viewDidLoad() {
super.viewDidLoad()

let nibFile : UINib = UINib(nibName: "DescriptionNearCollectionViewCell", bundle: nil)

descriptionCollectionView.register(nibFile, forCellWithReuseIdentifier: "descriptionCell")

let nibFile2 : UINib = UINib(nibName: "DescriptionImageSliderCollectionViewCell", bundle: nil)

descriptionCollectionView.register(nibFile2, forCellWithReuseIdentifier: "descriptionCell")
// Do any additional setup after loading the view.
}


Dequeue Reusable Cell:

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

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

Answer

You can't register more than one nib on a CollectionView with the same reuseIdentifier. Use a unique one for each:

override func viewDidLoad() {
    super.viewDidLoad()

    let nibFile : UINib =  UINib(nibName: "DescriptionNearCollectionViewCell", bundle: nil)

    descriptionCollectionView.register(nibFile, forCellWithReuseIdentifier: "descriptionCell")

    let nibFile2 : UINib =   UINib(nibName: "DescriptionImageSliderCollectionViewCell", bundle: nil)

    descriptionCollectionView.register(nibFile2, forCellWithReuseIdentifier: "descriptionCell2")
    // This >>                                                                               ^
}

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

    if (youWantCellOne) {
        return collectionView.dequeueReusableCell(withReuseIdentifier: "descriptionCell", for: indexPath)
    } else {
        return collectionView.dequeueReusableCell(withReuseIdentifier: "descriptionCell2", for: indexPath)
    }
}