【发布时间】:2022-01-01 03:22:29
【问题描述】:
背景:我的应用程序允许用户选择渐变边框以应用于根据其中的内容动态调整大小的 UITableViewCells。我目前正在通过将 CAGradientLayer 子层插入单元格内的 UIView 来创建此边框。
问题:因为每个单元格的大小不同,我通过在我的自定义单元格类中覆盖 layoutIfNeeded 来调整 CAGradientLayer 的大小。这可行,但似乎不是最理想的,因为边框被一遍又一遍地重绘,并且随着单元格大小的调整而闪烁。
屏幕截图链接: https://drive.google.com/file/d/1SiuNozyUM7LCdYImZoGCWeoeBKu2Ulcw/view?usp=sharing
问题:我是否需要采用不同的方法来创建此边框?或者我错过了关于 UITableViewCell 生命周期的一些东西?我在 SO 上遇到过类似的问题,但似乎没有一个可以解决这个重绘问题。感谢您的帮助。
CAGradientLayer 扩展创建边框
extension CAGradientLayer {
func createBorder(view: UIView, colors: [CGColor]) {
self.frame = CGRect(origin: CGPoint.zero, size: view.bounds.size)
self.colors = colors
let shape = CAShapeLayer()
shape.lineWidth = 14
shape.path = UIBezierPath(roundedRect: view.bounds, cornerRadius: 12).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
self.mask = shape
}
}
TableViewCell 类 - 插入 CAGradientLayer
override func awakeFromNib() {
super.awakeFromNib()
reportCard.layer.insertSublayer(gradientLayer, at: 0)
...
}
TableViewCell 类 - 调整边框大小并应用用户选择的设计
override func layoutIfNeeded() {
super.layoutIfNeeded()
switch currentReport?.frameId {
case "sj_0099_nc_frame_001":
gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.lavender, App.BorderColors.white])
case "sj_0099_nc_frame_002":
gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.red, App.BorderColors.white])
case "sj_0099_nc_frame_003":
gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.yellow, App.BorderColors.white])
default:
gradientLayer.createBorder(view: reportCard, colors: [App.BorderColors.white, App.BorderColors.white])
}
}
【问题讨论】:
标签: ios swift uitableview cagradientlayer