如何在一个 CollectionView 中加载多个 nib 文件?

How can I load multiple nib files in one CollectionView?

这只会加载 DescriptionImageSliderCollectionViewCell。我很确定这里发生了什么,但我想加载两者,但我不知道该怎么做。

我注册集合视图单元格的代码:

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

出列可重复使用的单元格:

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

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

您不能在具有相同 reuseIdentifier 的 CollectionView 上注册多个 nib。为每个使用一个唯一的:

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