Wayne Filkins
Wayne Filkins

Reputation: 524

How to reload a collectionview cell without reloading an image

I have a collection view and when something changes I update the data source and reload the cell in which the change occurs. The cell kind of blinks when it reloads. It doesn't really affect the user scrolling and I made it almost unnoticeable with:

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

This was the best I could do to make the reload less noticeable. I have a background image taking up the entire cell. I think the flash that I'm seeing is this image reloading, yet I don't need it to reload because the image will never change. Does anyone know how to make the cell reload but not the image? I can put a variable in there and change it such as (initalLoad = false) but I don't know how to keep the image from reloading.

Upvotes: 0

Views: 3243

Answers (1)

Austin Wood
Austin Wood

Reputation: 378

Try moving all your cell setup to an internal func in your UICollectionViewCell subclass:

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
    }

}

and then calling it from your view controller:

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

You can add parameters to the configureCell() function to pass in any data you need for setting up the cell (presumably you'll need to pass in some kind of reference to your image). If you have a lot of information, you might want to create a custom object to hold all that information, then pass that into the function as a parameter.

Upvotes: 1

Related Questions