首页 > 解决方案 > 在集合视图单元格中的 UIView 上设置渐变背景

问题描述

我有一个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()
}

wheresetGradientBackground被定义为 的扩展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本身也不起作用。

标签: iosswiftuicollectionviewuicollectionviewcell

解决方案


该视图bounds内部尚不为人所知,cellForRowAt而且当您滚动单元格出列时,它会添加许多渐变

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

推荐阅读