我正在更改每个 TableViewCell 的大小:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
然后,在自定义单元格类中,我将“gradientLayer”作为子层插入到单元格的图层属性中:
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
...
gradientLayer.frame = self.layer.bounds
layer.insertSublayer(gradientLayer, at: 0)
...
}
有谁知道为什么会这样/我该如何解决?
谢谢。
最佳答案
如果您使用普通的 UITableViewCell
:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
// ...
let gradient = CAGradientLayer()
gradient.frame = cell.contentView.frame
gradient.colors = [UIColor.blue.cgColor, UIColor.yellow.cgColor]
gradient.locations = [0.0, 1.0]
cell.contentView.layer.insertSublayer(gradient, at: 0)
// ...
return cell
}
您需要确保将渐变添加到 contentView 的层。
这会很好用。
如果您使用自定义 UITableViewCell
类:
现在,如果您使用的是自定义单元格类,则需要像这样重写layoutSubviews()
方法:
override func layoutSubviews() {
super.layoutSubviews()
gradient.frame = contentView.frame
}
这确保您的渐变框架在任何时候始终等于您的 contentView 框架。
您的自定义单元类将如下所示:
class CustomTableCell: UITableViewCell {
lazy var gradient : CAGradientLayer = {
var gradient = CAGradientLayer()
gradient.colors = [UIColor.blue.cgColor, UIColor.yellow.cgColor]
gradient.locations = [0.0, 1.0]
self.contentView.layer.insertSublayer(gradient, at: 0)
return gradient
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// ...
}
override func layoutSubviews() {
super.layoutSubviews()
// ...
gradient.frame = contentView.frame
// ...
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// ...
}
}
如果您还有其他问题,请告诉我!
关于ios - UITableViewCell 的层在 heightForRowAt IndexPath 之后没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333668/