【问题标题】:How to fix 'NSInternalInconsistencyException' error using UICollectionView in Swift?如何在 Swift 中使用 UICollectionView 修复“NSInternalInconsistencyException”错误?
【发布时间】:2019-09-25 20:10:35
【问题描述】:

我想在集合视图中显示我的数据。

我有一个UICollectionView 并设置了cellForItemAt 委托方法。这是我在cellForItemAt委托方法中尝试过的代码。

 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "productCell", for: indexPath) as! ProductCollectionViewCell

编辑代码(所有cellForItemAt委托方法):

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "productCell", for: indexPath) as! ProductCollectionViewCell

        let productSnapshot = products[indexPath.item]

        if let productsDictionary = productSnapshot.value as? NSDictionary{
            guard let productName = productsDictionary["name"] as? String else { return UICollectionViewCell() }
            guard let productPrice = productsDictionary["price"] as? Int else { return UICollectionViewCell() }
            guard let productCategory = productsDictionary["category"] as? String else { return UICollectionViewCell() }

            let product = Product(uid: productSnapshot.key, name: productName, price: productPrice, categoryUid: productCategory)

            cell.setProduct(product: product)
        }

        return cell

    }

这是错误信息:

“由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'从-collectionView:cellForItemAtIndexPath:返回的单元格没有reuseIdentifier - 必须通过调用-dequeueReusableCellWithReuseIdentifier:forIndexPath:'来检索单元格”

【问题讨论】:

  • 你能包括你的collectionView(cellForItemAtIndexPath:)函数的实现吗?还是那条线就是全部?
  • 这是您在该函数中拥有的唯一代码吗?您可以编辑问题以完整显示该委托功能吗?您显示的代码与异常消息不一致
  • 我编辑了代码。 @Paulw11

标签: ios swift uicollectionview


【解决方案1】:

您的问题是由所有这些 guard/else 语句引起的 - 如果任何 guards 失败,那么您将返回 UICollectionViewCell() - 正如异常所说,这是一个未正确出列的单元格。

确实,您的数据模型应该在达到这一点之前就已经过验证。 products 应该包含 Product 而不是 Dictionary 的实例。这样您就永远不会将无效产品加载到数据源数组中。

一旦你这样做了,你就可以简单地写

var products: [Product]

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "productCell", for: indexPath) as! ProductCollectionViewCell

    let product = products[indexPath.item]
    cell.setProduct(product: product)

    return cell

}

记住cellForItemAt: 可能会随着集合视图的滚动而被多次调用,因为它应该尽可能高效。尽管访问字典和创建Product 的开销并不大,但无需一次又一次地这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多