首页 > 解决方案 > 如果使用 (indexPath.item % n == 0) 显示单元格,则 UICollectionView 不会创建新单元格。它不会为数字的倍数创建新单元格

问题描述

我正在使用这个条件来创建特定的 UICollectionViewCells。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if(indexPath.item % 3 == 0){//multiples of 3
        let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "Cell1id", for: indexPath) as! Cell1
        cell.backgroundColor = .white

        if(cell.wasCreated){
            cell.cellLabel.text = "Cell(1) \(indexPath.item) was created before."
        }
        else{
            cell.cellLabel.text = "Creating cell(1) \(indexPath.item) first time."
            cell.wasCreated = true
        }

        return cell
    }
    else{
        let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "Cell2id", for: indexPath) as! Cell2
        cell.backgroundColor = .gray

        if(cell.wasCreated){
            cell.cellLabel.text = "Cell(2) \(indexPath.item) was created before."
        }
        else{
            cell.cellLabel.text = "Creating cell(2) \(indexPath.item) first time."
            cell.wasCreated = true
        }

        return cell
    }
}//end cellForItemAt

这里'wasCreated'是单元格中的一个变量,我用来检查单元格是否是第一次创建,如果它是我设置的wasCreated = true,这应该是第一次,对于每个单元格,但它不是不。条件是:如果indexPath.item是 3 的倍数,则 deque 单元格 1 否则为单元格 2。现在通常,当第一次显示单元格时,将调用单元格的 init() 方法,但在这种情况下它不会被调用,并且由于某种原因,较旧的单元格正在出队。我不知道为什么会这样。

我已经上传了一个重现问题的示例项目。这是链接: https ://github.com/AfnanAhmadiOSDev/IndexMultiplesTest.git

标签: iosswiftuicollectionview

解决方案


您描述的行为是预期的。为了减少内存使用,单元格在集合视图滚动时被重用。

当您调用dequeueReusableCellUIKit 时,会检查是否存在具有请求标识符的单元格已移出屏幕并因此可以重用。如果有,则返回此单元格。在这种情况下init不会被调用。如果没有候选单元格,则返回一个新的单元格实例init并将被调用。

当您运行代码时,您会首先看到正在创建单元格,但是在您向上和向下滚动以构建足够大的单元格重用池之后,单元格将被重新使用并且不会创建新单元格。

单元重用与IndexPath之前使用单元的目的无关。


推荐阅读