iOS - How to apply gradient color to UICollectionViewCell backgroundView?

こ雲淡風輕ζ 提交于 2019-12-11 02:56:08

问题


I have been able to apply the gradient I want to the backgroundView of my UICollectionViewCell. But every time I reload the cell, it applies again my gradient, accumulating all the gradient.

First of all here is my method for the gradient :

static func setGradientWhite(uiView: UIView) {

    let colorBottomWhite = UIColor(red:1.00, green:1.00, blue:1.00, alpha:0.30).cgColor
    let colorTopWhite = UIColor(red:1.00, green:1.00, blue:1.00, alpha:0).cgColor

    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [ colorTopWhite, colorBottomWhite]
    gradientLayer.locations = [ 0.0, 1.0]
    gradientLayer.frame = uiView.bounds

    uiView.layer.insertSublayer(gradientLayer, at: 0)
}

I know I can do it in a more generic way, and change the way I am handling the colors, but it's not the point, it is for testing purpose for now.

I tried to call it like this :

override func awakeFromNib() {
     super.awakeFromNib()
     UIUtils.setGradientWhite(uiView: self)
}

The gradients do not accumulate this way, in the awakeFromNib, BUT, the animation isn't finish and I only have half of my cell with gradient applied.

And if I do it in this method :

override func layoutSubviews() {
     super.layoutSubviews()

     CATransaction.begin()
     CATransaction.setDisableActions(true)
     UIUtils.setGradientWhite(uiView: self)
     CATransaction.commit()
}

The gradient animation is properly finished, applying to the whole view, but when the cell is reloading, it applies a new gradient on top of the previous one, until I cannot see my cell anymore (in this case too much white here).

Any ideas on how can I solve this issue?


回答1:


You can try

override func layoutSubviews() {
   super.layoutSubviews() 
   if !(self.layer.sublayers?.first is CAGradientLayer) { 
       CATransaction.begin()
       CATransaction.setDisableActions(true)
       UIUtils.setGradientWhite(uiView: self)
       CATransaction.commit()
   }
}


来源:https://stackoverflow.com/questions/53393925/ios-how-to-apply-gradient-color-to-uicollectionviewcell-backgroundview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!