我有一个有点奇怪的 UITableView 子类:它有一个超出单元格边界的 subview 。我在初始化期间添加了这个 subview :
class MyCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(self.subviewThatGoesOutOfBounds)
}
...
}
现在,当我为呈现此单元格的 TableView 启用分隔线时,我注意到此单元格的分隔线显示在 subview 上方,它超出了单元格的边界.在 View 层次检查器的帮助下,我可以看到分隔线是一个 View ,并且它呈现在我的 subview 前面。
我想我可以通过将 subview 放在前面,或者在添加分隔线后等待将其添加为 subview 来解决这个问题。但那会是细胞生命周期中的哪一点?
最佳答案
表格 View 单元格在布局过程中设置其层次结构(作为表格 View )。您可以使用调试器轻松发现它:
class TableViewCell: UITableViewCell {
override func layoutSubviews() {
contentView.printHierarchy() // one UITableViewLabel
super.layoutSubviews()
contentView.printHierarchy() // one UITableViewCellSeparatorView
}
}
在幕后,细胞使用 UITableViewCellLayoutManager它根据表格 View 单元格的样式定义要添加或删除的 subview 。
这种行为可能会改变。我建议删除 native 分隔符(使用 separatorStyle = .none
)并添加您自己的分隔符 subview 。这样,如果 UITableViewCell 发生变化,您的代码仍然可以使用。否则,如果您不介意,请在 super.layoutSubviews
之后添加您的 subview 或将其置于最前面。
关于ios - 在 UI 生命周期的哪一点,分隔线作为 subview 添加到 UITableViewCells?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54286483/