Search code examples
iosswiftuicollectionviewuicollectionviewcell

Dynamically handle the background and foreground colors inside UICollectionViewCell's elements


I have a UICollectionViewCell which contains a UIView enclosing a UILabel. I have to change the background color of UIView and the text color of UILabel on the base of a boolean value. The colors on the base of the boolean value work find unless I add the fourth item in the UICollectionView. All items from all previous and current cells get the same respective color like that of the items of the fourth cell as soon as I add the fourth item.

The problem is exactly related to this but here I cannot add the colors in the init method of UICollectionViewCell and then activate/deactivate them in cellForRowAt on the basis of the boolean value. What could I do to resolve this?


Solution

  • Reset the colors of UIView and UILabel in prepareForReuse() method of your custom UICollectionViewCell.

    Example:

    class CustomCell: UICollectionViewCell {
        @IBOutlet weak var customView: UIView!
        @IBOutlet weak var label: UILabel!
    
        override func prepareForReuse() {
            super.prepareForReuse()
    
            //reset the colors here.........
            customView.backgroundColor = .white
            label.textColor = .black
        }
    }