1

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

ShrikantWalekar
  • 145
  • 1
  • 6
  • 1
    Please show the relevant code regarding the *specific* problem. The link to the entire project isn't bad, but put a block of code that's not working the way you expect into your question. Be more specific about the problem itself, too. – Smartcat Oct 30 '18 at 04:44
  • 1
    And also upload image what result exactly need? – V D Purohit Oct 30 '18 at 05:04
  • I guess you are applying the gradient when the cell size hasn't been set yet. When it's been set, changes the bounds of the gradient layer to the one of the cell. – Larme Oct 30 '18 at 07:08

1 Answers1

6

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?

V D Purohit
  • 1,179
  • 1
  • 10
  • 23
Niki
  • 1,566
  • 1
  • 19
  • 36