iOS - 如何将渐变颜色应用于 UICollectionViewCell backgroundView?

iOS - How to apply gradient color to UICollectionViewCell backgroundView?

我已经能够将我想要的渐变应用于我的 UICollectionViewCell 的背景视图。但是每次我重新加载单元格时,它都会再次应用我的渐变,累积所有渐变。

首先是我的渐变方法:

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)
}

我知道我可以用更通用的方式做到这一点,并改变我处理颜色的方式,但这不是重点,现在只是为了测试目的。

我试着这样称呼它:

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

渐变不会以这种方式累积,在 awakeFromNib 中,但是,动画还没有完成,我只有一半的单元格应用了渐变。

如果我用这种方法来做:

override func layoutSubviews() {
     super.layoutSubviews()

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

渐变动画已正确完成,应用于整个视图,但是当重新加载单元格时,它会在前一个单元格之上应用新的渐变,直到我再也看不到我的单元格(在这种情况下太多了这里是白色)。

关于如何解决这个问题有什么想法吗?

你可以试试

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