How to clear a UICollectionViewCell on reload?

Use prepareForReuse method in your custom cell class, something like this:

override func prepareForReuse() {
    super.prepareForReuse()
    //hide or reset anything you want hereafter, for example
    label.isHidden = true
}

in your cellForItemAtIndexPath, instantiate your custom cell:

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellIdentifier", for: indexPath) as! CustomViewCell

Then, always in cellForItemAtIndexPath, setup your items visibility/values


UICollectionViewCells are reused to avoid instantiations, to optimize the performance. If you are scrolling and a cell becomes invisible, the same object is used again (dequeueReusableCell) and a new content is set in cellForItemAt...

As mentioned in the previous answers, before reusing the cell, prepareForReuse() is called on the cell. So you can overrride prepareForReuse() and do whatever preparation you need to do.

You are however creating and adding a new EYPlayerHUDView to the cell on every reuse, so your cell becomes full of stacked EYPlayerHUDViews.

To avoid this, subclass UICollectionViewCell and make the EYPlayerHUDView a property of your custom cell (I recommend to use a XIB):

class MyCell: UICollectionViewCell {
    @IBOutlet var player:EYPlayerHUDView!

    override func prepareForReuse() {
        super.prepareForReuse()
        // stop your player here
        // set your label text = ""
    }
}

After doing so, you can update the EYPlayerHUDView in cellForItemAt without instantiating it and without adding it as new view:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifer, for: indexPath) as? MyCell else {
        return nil
    }

    if let allPlayers = self.allPlayers {
        let player:EYPlayer = allPlayers[indexPath.row]
        cell.player.updatePlayerHUD(player: player)
    }

    return cell
}

(Code untested)


//cell = UICollectionViewCell
for subview in cell.contentView.subviews {
     // you can place "if" condition to remove image view, labels, etc.
     //it will remove subviews of cell's content view
     subview.removeFromSuperview()
}