首页 > 解决方案 > 如何在集合视图中正确呈现渐变视图?

问题描述

以下是我用来渲染具有渐变视图的项目的集合视图委托函数。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    collectionView.layoutIfNeeded()

    let collectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell

    let gradient = CAGradientLayer()

    gradient.frame = collectionView.bounds

    gradient.startPoint = CGPoint(x: 0.0, y: 0.5)

    gradient.endPoint = CGPoint(x: 1.0, y: 0.5)

    if indexPath.row % 2 == 0 {
        gradient.colors = [UIColor(hex: 0xD74F9B).cgColor, UIColor(hex: 0xF1828A).cgColor]
    } else {
        gradient.colors = [UIColor(hex: 0x5368D3).cgColor, UIColor(hex: 0x4AAAD1).cgColor]
    }

    collectionViewCell.cardView.layer.insertSublayer(gradient, at: 0)

    return collectionViewCell
}

加载集合视图时,我得到以下视图,其中一个集合视图项被剪裁。 在此处输入图像描述

但是,当我滚动集合视图时,我得到了正确渲染的视图。 在此处输入图像描述

如何解决这个问题?

标签: iosswiftuicollectionviewgradient

解决方案


问题是当您添加渐变视图时,bgView 没有完全布局。所以界限将为零。

解决方案:

 // CollectionViewCell.swift
private var gradient: CAGradientLayer?

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

    override func layoutSubviews() {
        super.layoutSubviews()

        shadowView.layer.shadowPath = UIBezierPath(rect: shadowView.bounds).cgPath

        if let gradient = gradient {
            gradient.frame = bgView.bounds
        } else {
            gradient = CollectionViewCell.createGradientLayer(for: bgView)
            bgView.layer.addSublayer(gradient!)
        }
    }

推荐阅读