【发布时间】: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