【问题标题】:Gradient background color of UICollection View Cell changes by itself while scrolling集合视图单元格的渐变背景颜色在滚动时自行更改
【发布时间】:2021-03-30 17:16:23
【问题描述】:

我有以下cellForRow 代码

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SquareCVC", for: indexPath) as! SquareCVC
if let gradient1 = items[indexPath.row].hex_up, let gradient2 = items[indexPath.row].hex_down{
     cell.contentView.setGradientBackground(firstColor: gradient1, secondColor: gradient2)
}else{
     cell.contentView.setGradientBackground(firstColor: "#EFEFF1", secondColor: "#EFEFF1")
}

但是当我滚动集合视图时,背景颜色会自行改变 有我的 setGradientBackground 函数

func setGradientBackground(firstColor: String, secondColor: String) {
        let colorTop =  colorWithHexString(hexString: firstColor).cgColor
        let colorBottom = colorWithHexString(hexString: secondColor).cgColor
                    
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.frame = self.bounds
                
        self.layer.insertSublayer(gradientLayer, at:0)
    }

有什么想法吗?

【问题讨论】:

标签: ios swift collectionview


【解决方案1】:

可能的问题:

  • 您每次都插入一个图层。单元格被重复使用,您可能为每个单元格添加了 300 层,以便滚动太多。除非你覆盖prepareForReuse()并删除每个CAGradientLayer,但最好直接有一个实例变量。

  • 您在单元格获得完整帧之前设置边界。使用layoutSubviews()

class YourCollectionViewCell: UICollectionViewCell {
    var gradientLayer = CAGradientLayer()

    func setGradientBackground(firstColor: String, secondColor: String) {
        let colorTop =  colorWithHexString(hexString: firstColor).cgColor
        let colorBottom = colorWithHexString(hexString: secondColor).cgColor                
        gradientLayer.colors = [colorTop, colorBottom]

        if gradientLayer.superlayer == nil { //Or insert it on init
            layer.insertSublayer(gradientLayer, at:0)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        gradient.frame = bounds
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多