UICollectionViewCell,多个单元格大小,设置 gradientView 宽度未设置为当前单元格大小,滚动时有时会发生变化

UICollectionViewCell, multiple cell size, set gradientView width not set to the current cell size and sometimes changes when scrolling

我在这个 class 中有 2 种尺寸的单元格,这让我遇到了很多麻烦,因为我必须为单元格设置底部 gradientView。 当我第一次打开 viewController 时,一切都设置正确,除了有时渐变视图颜色在某些单元格中看起来不一样,但真正的问题开始于您开始滚动时,底部渐变视图在大单元格和渐变颜色真的很糟糕,正如您在下图中看到的那样,有些具有非常深的颜色作为底部颜色,有些具有淡黄色,这使得单元格看起来不一样

我如何设置单元格大小:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchProductsCell", for: indexPath) as! SearchProductsCell
    cell.configCell(data: data[indexPath.row])
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let smallCellSize : CGFloat =  self.collectionView.frame.height  / 2.11
    let height = indexPath.row % 3 == 0 ? self.collectionView.frame.height  : smallCellSize
     return CGSize(width: height, height: height)
}

这就是单元格 class 设置:

 class SearchProductsCell: UICollectionViewCell {

@IBOutlet weak var imageV: UIImageView!
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var gradientView: UIView!

var isGradientAdded = false

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func prepareForReuse() {
    super.prepareForReuse()
}


func configCell(data : Product_Data ) {

    let img = data.image == "" ? data.thumb : data.image
    imageV.setupApiImage(imagePath: img)
    titleLbl.text = data.name
    if isGradientAdded == false {
        addGradient()
        isGradientAdded = true
    }
}

func addGradient () {
    let gradient = CAGradientLayer()
    gradient.frame = self.bounds
    let topColor = UIColor.yellow
    let botomColor = UIColor.red
    gradient.colors = [topColor.cgColor, botomColor.cgColor]
    gradientView.layer.insertSublayer(gradient, at: 0)
} 

    }

由于单元重复使用,您的 gradient frame 将在单元几何形状发生变化时变得过时。

在您的 SearchProductsCell class 中,在 layoutSubviewsoverride 中更新 gradientframe

override func layoutSubviews() {
    super.layoutSubviews()
    if isGradientAdded {
        gradientView.layer.sublayers?.first?.frame = self.bounds
    }
}