ios - UITableViewCell 背景渐变在第一次渲染时不起作用
问题描述
我有一个表格视图。我使用 xib 文件创建我的单元格。
我需要 1 个单元格(即当前用户)作为渐变背景,我创建了一个背景渐变层,但它不适合查看。在我下拉列表后,它可以工作。
你可以看到我的截图,这是我的代码
//In the table cell,
if data.userUniqueId != nil && userUIID != nil && data.userUniqueId! == userUIID! {
let startColor = UIColor(red: 253/255.0, green: 162/255.0, blue: 75/255.0, alpha: 1)
let endColor = UIColor(red:251/255.0, green:215/255.0, blue: 126/255.0, alpha:1)
self.setGradient(colors: [startColor.cgColor, endColor.cgColor],angle: 90)
self.layer.borderColor = UIColor.white.cgColor
self.layer.borderWidth = 2
number.textColor = UIColor.white
}
这是梯度法
func setGradient(colors: [CGColor], angle: Float = 0) {
let gradientLayerView: UIView = UIView(frame: CGRect(x:0, y: 0, width: bounds.width, height: bounds.height))
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = gradientLayerView.bounds
gradient.colors = colors
let alpha: Float = angle / 360
let startPointX = powf(
sinf(2 * Float.pi * ((alpha + 0.75) / 2)),
2
)
let startPointY = powf(
sinf(2 * Float.pi * ((alpha + 0) / 2)),
2
)
let endPointX = powf(
sinf(2 * Float.pi * ((alpha + 0.25) / 2)),
2
)
let endPointY = powf(
sinf(2 * Float.pi * ((alpha + 0.5) / 2)),
2
)
gradient.endPoint = CGPoint(x: CGFloat(endPointX),y: CGFloat(endPointY))
gradient.startPoint = CGPoint(x: CGFloat(startPointX), y: CGFloat(startPointY))
gradientLayerView.layer.insertSublayer(gradient, at: 0)
layer.insertSublayer(gradientLayerView.layer, at: 0)
}
以及如何从图层中删除渐变以供下次使用单元格?
编辑: 表视图代码
extension RecordsViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return values.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ScoreBoardCell", for: indexPath) as? ScoreBoardCell {
let score = self.values[indexPath.row]
cell.setData(indexPath.row, score)
cell.selectionStyle = .none
return cell
}
return UITableViewCell()
}
}
解决方案
问题是这一行:
gradient.frame = gradientLayerView.bounds
在这段代码运行的时候cellForRowAt
,你的gradientLayerView
还没有完全布局,所以bounds
还不知道。因此,在布局确实发生后,您将gradient
使用不适合其视图的 a 。frame
我认为cell.setData
您可以通过将调用移动到来解决问题tableView(_:willDisplay:forRowAt:)
,此时应该知道单元格大小。
以及如何从图层中删除渐变以供下次使用单元格?
好吧,这里的问题是您的情况别无选择:
if data.userUniqueId != nil && userUIID != nil && data.userUniqueId! == userUIID!
问题是:如果不是怎么办?在这种情况下,如果已添加渐变层,则需要将其移除。你没有为这种情况提供任何逻辑。— 你也需要小心,因为如果已经添加了渐变层并且你的逻辑现在导致你添加另一个渐变层怎么办?基本上,您的整个方法没有考虑到关于表格视图单元格的最基本事实,即它们被重用。
推荐阅读
- c# - 如何根据另一个下拉列表 ASP.NET 的选择填充下拉列表
- javascript - React Konva 中正多边形的捕捉问题
- c# - 从动作中检索朴素的动作名称
- r - 包功能中的单元测试和检查:我们是否都进行检查?
- mysql - 从 MySQL 迁移到 SQL Server,如何实现触发器
- c# - JObject 解析返回额外的花括号
- flutter - 完成迭代循环后地图为空
- javascript - 如何在不更改原始行的情况下修改“克隆”行
- ios - 快速注销时未捕获 AppAuth 缓存问题/通用链接
- asp.net-mvc - 如何跨层移动数据(MVC5 + EF6 + DDD)?