user7087846
user7087846

Reputation:

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
}

Upvotes: 2

Views: 1665

Answers (1)

brandonscript
brandonscript

Reputation: 72965

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)
    }
}

Upvotes: 4

Related Questions