0

I have the following cellForRow code

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SquareCVC", for: indexPath) as! SquareCVC
if let gradient1 = items[indexPath.row].hex_up, let gradient2 = items[indexPath.row].hex_down{
     cell.contentView.setGradientBackground(firstColor: gradient1, secondColor: gradient2)
}else{
     cell.contentView.setGradientBackground(firstColor: "#EFEFF1", secondColor: "#EFEFF1")
}

But when I scroll collection view, background color changes by itself There is my setGradientBackground function

func setGradientBackground(firstColor: String, secondColor: String) {
        let colorTop =  colorWithHexString(hexString: firstColor).cgColor
        let colorBottom = colorWithHexString(hexString: secondColor).cgColor
                    
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.frame = self.bounds
                
        self.layer.insertSublayer(gradientLayer, at:0)
    }

Any ideas?

1 Answers1

1

Possible issues:

  • You are inserting EACH time a layer. Cells are reused, you might have 300 layers added up for each cells for scrolling too much. Except if you override prepareForReuse() and remove each CAGradientLayer, but it'd be better to have an instance variable directly.

  • You are settings the bounds BEFORE the cell got its full frame. Use layoutSubviews()

class YourCollectionViewCell: UICollectionViewCell {
    var gradientLayer = CAGradientLayer()

    func setGradientBackground(firstColor: String, secondColor: String) {
        let colorTop =  colorWithHexString(hexString: firstColor).cgColor
        let colorBottom = colorWithHexString(hexString: secondColor).cgColor                
        gradientLayer.colors = [colorTop, colorBottom]

        if gradientLayer.superlayer == nil { //Or insert it on init
            layer.insertSublayer(gradientLayer, at:0)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        gradient.frame = bounds
    }

}
Larme
  • 24,190
  • 6
  • 51
  • 81