ios - 如何在集合视图中正确呈现渐变视图?
问题描述
以下是我用来渲染具有渐变视图的项目的集合视图委托函数。
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
}
如何解决这个问题?
解决方案
问题是当您添加渐变视图时,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!)
}
}
推荐阅读
- api - Flutter 使聊天屏幕出现在 api 中获取或发送消息
- sql - 如何在 PostgreSQL 中获取移动窗口 argmax
- python - python删除xml文件上的注释
- r - 在 annotate() 中使用 npc 单位
- bash - Control-m 运行时变量:sh vs powershell
- javascript - Angular 5 - TypeError: Object does not support this action on IE11- PolyFills 需要支持吗?
- python - 如何让 pd.to_datetime() 采用多种日期格式?
- javascript - javascript url参数从url中取出中心字符串
- xml - 有没有一种方法可以使用 saxon 从文本列表中调用 xQuery 函数?
- javascript - 如何引用 id 并获取链接的 href?