ios - 如何在 Collection View 中正确渲染渐变 View ?

标签 ios swift uicollectionview gradient

以下是我用来渲染具有渐变 View 的项目的 Collection View 委托(delegate)函数。

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
}

加载 Collection View 时,我得到以下 View ,其中 Collection View 项目之一被剪裁。 enter image description here

但是,当我滚动 Collection View 时,我得到了正确渲染的 View 。 enter image description here

如何解决这个问题?

最佳答案

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

关于ios - 如何在 Collection View 中正确渲染渐变 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53650349/

相关文章:

ios - 如何从代表的 Collection View 单元格中获取 indexPath 项?

ios - 在不同的设备方向上更改 UICollectionViewCell 大小

iphone - UITableView 行选择与 UIPicker 选项

ios - 在 Swift 中获取网页 HTML 代码

iOS7 iPad Landscape only app,使用 UIImagePickerController

swift - 如何缩进 UITextView 中的部分文本

IOS 使用 presentModalViewController 显示一些 Controller

ios - 调整图像大小而不损失质量

ios - 在 Swift 中以编程方式添加时,UIScrollView 根本不滚动吗?

ios - 对 UICollectionView 中的特定单元格进行动画处理