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

时间:2016-10-24 17:49:34

标签: ios swift uicollectionview uicollectionviewcell

我有一个集合视图,当有什么变化时,我更新数据源并重新加载发生变化的单元格。重新加载时,单元格会闪烁。它并没有真正影响用户滚动,我用它几乎无法察觉:

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

这是我能做的最好的工作,使重新加载不那么引人注目。我有一个背景图像占据了整个细胞。我认为我看到的闪光灯是重新加载的图像,但我不需要重新加载,因为图像永远不会改变。有谁知道如何使细胞重新加载而不是图像?我可以在其中放置一个变量并更改它,例如(initalLoad = false),但我不知道如何防止图像重新加载。

1 个答案:

答案 0 :(得分:1)

尝试将所有单元格设置移动到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()函数添加参数,以传入设置单元格所需的任何数据(可能您需要传递某种对图像的引用)。如果您有大量信息,可能需要创建一个自定义对象来保存所有信息,然后将其作为参数传递给函数。

相关问题