ios - 在集合视图单元格中的 UIView 上设置渐变背景
问题描述
我有一个UICollectionViewCell
包含一个UIView
我想在其上设置渐变背景的内容。这是我的cellForItemAt
方法:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell: PaymentMethodCVCell = collectionView.dequeueReusableCell(withReuseIdentifier: "paymentMethodCVCell", for: indexPath) as? PaymentMethodCVCell {
let row = indexPath.row
cell.rewardsCard.setGradientBackground(colorTop: appRed, colorBottom: appRed.darkerColor(), withCornerRadius: 10)
return cell
}
return UICollectionViewCell()
}
wheresetGradientBackground
被定义为 的扩展UIView
:
func setGradientBackground(colorTop: UIColor, colorBottom: UIColor, withCornerRadius : CGFloat){
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [colorBottom.cgColor, colorTop.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.0)
gradientLayer.locations = [0, 1]
gradientLayer.frame = bounds
gradientLayer.cornerRadius = withCornerRadius
layer.insertSublayer(gradientLayer, at: 0)
}
这工作正常,但只有当我在中向上和向下滚动并且UICollectionView
重新加载单元格时 - 最初加载到页面上的单元格没有正确设置背景。这样做UICollectionViewCell
本身也不起作用。
解决方案
该视图bounds
内部尚不为人所知,cellForRowAt
而且当您滚动单元格出列时,它会添加许多渐变
gradientLayer.frame = bounds
所以在细胞内
var once = true
override func layoutSubviews() {
super.layoutSubviews()
if once {
// add gradient
once = false
}
}
或者
override func layoutSubviews() {
super.layoutSubviews()
if !(rewardsCard.layer.sublayers?.first is CAGradientLayer ) {
// add gradient
}
}
推荐阅读
- python - 有没有更有效的方法来获得结果(O(n + m)而不是O(n * m))?
- algorithm - 如何使用 bfs 算法找到边界点
- sql - 按顺序查找范围
- python - Python Kuyruk 工人在后台
- angular - 在没有自定义管道的模板中对对象进行角度变换
- excel - 创建矩阵 3:常量 * 矩阵 1 + (1-常量) * 矩阵 2
- javascript - 如何在 Angular 中发出获取请求以接收 Wordpress 的 Gravityforms 数据?
- dhall - Dhall协会名单
- c# - 无法将 Active Directory 用户添加到 Azure SQL
- angular - 如何在 Angular 4 中刷新日期