I have a gradient background for my collection view cell and each gradient is different depending on what tag the cell is (e.g Christmas is a purple gradient, birthday is a
Reading your code in setGradientBackground()
, you always init a new CAGradientLayer
and insert it at the lowest position in your cell. Every time setGradientBackground()
gets called again, the new gradient layer will be positioned below all other gradients you already inserted.
Try to get a already existing CAGradientLayer
from sublayers and set the new colors.
var gradientLayer = CAGradientLayer()
if let sublayers = layer.sublayers {
for sublayer in sublayers {
if let gLayer = sublayer as? CAGradientLayer {
gradientLayer = gLayer
break
}
}
}
gradientLayer.frame = bounds
gradientLayer.colors = colours
gradientLayer.locations = [0.0, 1.0]
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.0)
layer.insertSublayer(gradientLayer, at: 0)
EDIT
This is a more swift like version (Swift 4.2) using compactMap()
for getting the first existing gradient layer in layer.sublayers
:
if let existingLayer = (layer.sublayers?.compactMap { $0 as? CAGradientLayer })?.first {
gradientLayer = existingLayer
}