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

我有一个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:来检索单元格:“

最佳答案

您的问题是由所有这些guard/else语句引起的-如果任何guard失败,那么您将返回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并没有很大的开销,但无需一次又一次地进行操作。

10-08 18:20