Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a UICollectionViewCell on reload?

I have an issue where the data presented in a UICollectionView overwrites the label and the cell view is not getting cleared.

This image shows the issue,

IE:

UICollectionViewCell data is not getting cleared

My UICollectionViewCell which is constructed like so;

// in viewDidLoad
self.playerHUDCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier:reuseIdentifer)

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifer, for: indexPath) as UICollectionViewCell
    let arr = UINib(nibName: "EYPlayerHUDView", bundle: nil).instantiate(withOwner: nil, options: nil)
    let view = arr[0] as! EYPlayerHUDView
    cell.contentView.addSubview(view)
    if let allPlayers = self.allPlayers
    {
        let player:EYPlayer = allPlayers[indexPath.row]
        view.updatePlayerHUD(player: player)
    }
    cell.layoutIfNeeded()
    return cell
}

I use a view to display in the cell.

I tried removing all the cell's subchildren in the cellForItemAt but it appears to remove all the subviews.

I would like to know how do I clear the UICollectionViewCell so labels and other info on the UICollectionViewCell is not dirty like the example above.

Many thanks

like image 641
zardon Avatar asked Apr 04 '17 08:04

zardon


2 Answers

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

like image 200
carmine Avatar answered Sep 18 '22 14:09

carmine


//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()
}
like image 42
Mahendra Avatar answered Sep 22 '22 14:09

Mahendra