【问题标题】:How to properly render gradient view in a collection view?如何在集合视图中正确呈现渐变视图?
【发布时间】:2018-12-06 11:23:21
【问题描述】:

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

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
}

加载集合视图时,我得到以下视图,其中一个集合视图项被剪裁。

但是,当我滚动集合视图时,我得到了正确渲染的视图。

如何解决这个问题?

【问题讨论】:

  • 不要这样做collectionViewCell.cardView.layer.insertSublayer(gradient, at: 0),单元格被重复使用。而是使用自定义单元格var gradient 的属性。在 cellInit 的 awakFromNib 中初始化/插入它(取决于您是否注册了 xib 或类)。当单元格布局发生变化时更新其框架,并且仅在 cellForRowAt 中更新其颜色。

标签: ios swift uicollectionview gradient


【解决方案1】:

问题是当你添加渐变视图时,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!)
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多