iOS Gradient color isse in collection view cell

2k views Asked by At

I am facing this issue while setting gradient color to view inside the collection view

When its plotted at first time its fine. but when I select some option and reload collection for the same it's happening like the second image.

viccalexander/Chameleon (https://github.com/viccalexander/Chameleon)

enter image description here

enter image description here

1

There are 1 answers

4
Niki Trivedi On

Try below code, might help you

  extension UIView{
        func addGradientBackground(firstColor: UIColor, secondColor: UIColor){
            clipsToBounds = true
            let gradientLayer = CAGradientLayer()
            gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor]
            gradientLayer.frame = self.bounds
            gradientLayer.startPoint = CGPoint(x: 0, y: 0)
            gradientLayer.endPoint = CGPoint(x: 0, y: 1)
            print(gradientLayer.frame)
            self.layer.insertSublayer(gradientLayer, at: 0)
        }
    }

And inside your cell simply:

override func awakeFromNib() {
    super.awakeFromNib()
    DispatchQueue.main.async {
        self.addGradientBackground(firstColor: .green, secondColor: .blue)
    }
}

Add this line only in Xib file otherwise when cell be reload then is add multiple Gradient in cell self.addGradientBackground(firstColor: .green, secondColor: .blue)

Reference - How to make cells have a gradient background?