如何在不重新加载图像的情况下重新加载 collectionview 单元格

How to reload a collectionview cell without reloading an image

我有一个集合视图,当某些内容发生变化时,我会更新数据源并重新加载发生变化的单元格。细胞在重新加载时会闪烁。它并没有真正影响用户滚动,我用它几乎不引人注意:

UIView.performWithoutAnimation{
     self.collectionView.reloadItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
}

这是我为使重新加载不那么引人注意所能做的最好的事情。我有一张背景图片占据了整个单元格。我认为我看到的闪光灯是这个图像重新加载,但我不需要它重新加载,因为图像永远不会改变。有谁知道如何重新加载单元格而不是图像?我可以在那里放一个变量并更改它,例如 (initalLoad = false) 但我不知道如何防止图像重新加载。

尝试将所有单元格设置移动到 UICollectionViewCell 子类中的内部函数:

class MyCollectionViewCell: UICollectionViewCell {

    var initialLoad = true

    // since collection view cells are recycled for memory efficiency,
    // you'll have to reset the initialLoad variable before a cell is reused
    override func prepareForReuse() {
        initialLoad = true
    }

    internal func configureCell() {

        if initialLoad {
            // set your image here
        }

        initialLoad = false

        // do everything else here
    }

}

然后从您的视图控制器中调用它:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell
    cell.configureCell()
    return cell
}

您可以向 configureCell() 函数添加参数以传递设置单元格所需的任何数据(大概您需要传递对图像的某种引用)。如果您有大量信息,您可能想要创建一个自定义对象来保存所有这些信息,然后将其作为参数传递到函数中。