gradient keeps switching between cells in collection view in swift

前端 未结 1 502
耶瑟儿~
耶瑟儿~ 2021-01-06 20:16

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

相关标签:
1条回答
  • 2021-01-06 20:36

    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
    }
    
    0 讨论(0)
提交回复
热议问题