以下是我用来渲染具有渐变 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 项目之一被剪裁。
但是,当我滚动 Collection View 时,我得到了正确渲染的 View 。
如何解决这个问题?
最佳答案
问题是当您添加渐变 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/