以下是我用来用渐变视图渲染项目的集合视图委托函数。
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
}
如何解决此问题?
答案 0 :(得分:0)
问题是,当您添加渐变视图时,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!)
}
}