在 Collection View Cell 的 UIView 上设置渐变背景

Setting Gradient Background on UIView in Collection View Cell

我有一个 UICollectionViewCell,其中包含一个 UIView,我想在其上设置渐变背景。这是我的 cellForItemAt 方法:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell: PaymentMethodCVCell = collectionView.dequeueReusableCell(withReuseIdentifier: "paymentMethodCVCell", for: indexPath) as? PaymentMethodCVCell {
           let row = indexPath.row
           cell.rewardsCard.setGradientBackground(colorTop: appRed, colorBottom: appRed.darkerColor(), withCornerRadius: 10)
           return cell
    }

    return UICollectionViewCell()
}

其中 setGradientBackground 定义为 UIView 的扩展:

func setGradientBackground(colorTop: UIColor, colorBottom: UIColor, withCornerRadius : CGFloat){
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor]
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
        gradientLayer.locations = [0, 1]
        gradientLayer.frame = bounds
        gradientLayer.cornerRadius = withCornerRadius
        layer.insertSublayer(gradientLayer, at: 0)
}

这工作正常,但只有当我在 UICollectionView 中上下滚动并重新加载单元格时 - 最初加载到页面上的单元格没有正确设置背景。在 UICollectionViewCell 中执行此操作本身也不起作用。

视图 boundscellForRowAt 中尚不为人所知,而且当您滚动时,它会添加许多渐变,因为单元格出队

gradientLayer.frame = bounds

所以在单元格内

var once = true

override func layoutSubviews() {
   super.layoutSubviews()
    if once {
        // add gradient
        once = false
    }
 } 

override func layoutSubviews() {
   super.layoutSubviews()
    if !(rewardsCard.layer.sublayers?.first is CAGradientLayer ) {
        // add gradient 
    }
 }