如何使用 XIB - Swift 将自定义 collectionviewCell 连接到重用标识符



我正在使用XIB制作自定义集合视图单元格。

集合视图作为扩展放置在视图控制器内。

这是我用来调用 Xib View 的代码,但我收到一个错误,告诉我需要使用重用标识符。但是我不知道在使用 XIB 时如何使用它。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = Bundle.main.loadNibNamed("CustomCell", owner: self, options: nil)?.first as! CustomCell
        return cell
    }

由于未捕获的异常"NSInternalInconsistencyException"而终止应用程序,原因:"从 -collectionView:cellForItemAtIndexPath: 返回的单元格没有重用标识符 - 必须通过调用 -dequeueReuseableCellWithReuseIdentifier:forIndexPath:' 来检索单元格:' 第一个抛出调用堆栈:

首先,您需要为单元格创建一个 reuseIdentifier。让我们根据您的集合视图单元格类名创建它。在 ViewController 文件中声明 reuseId:

let reuseId = String(describing: CustomCell.self)

您需要将单元格注册到集合ViewViewDidLoad方法。

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

然后在您的cellForItemAt方法中:

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

注册CustomCell,例如,

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

并在cellForItemAt中使用相同的注册单元格,例如,

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

适用于 Swift 4.0 和 4.2

在您看来,确实加载:

自定义集合视图单元格

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

在 cellForItemAt indexPath 中:

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

并且不要忘记在xib部分中为您的自定义单元格设置标识符。

最新更新