Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/116.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在集合视图单元格中的UIView上设置渐变背景_Ios_Swift_Uicollectionview_Uicollectionviewcell - Fatal编程技术网

Ios 在集合视图单元格中的UIView上设置渐变背景

Ios 在集合视图单元格中的UIView上设置渐变背景,ios,swift,uicollectionview,uicollectionviewcell,Ios,Swift,Uicollectionview,Uicollectionviewcell,我有一个UICollectionViewCell,其中包含一个UIView,我想在其上设置渐变背景。这是我的cellForItemAt方法: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell: PaymentMethodCVCell = collectionView.dequ

我有一个
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
中执行此操作本身也不起作用

cellForRowAt
中还不知道视图
bounds
,另外,当您滚动单元格时,它会添加许多渐变

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