有一个屏幕(UIViewController
)和一个表格(UITableView
)。该表的单元格在单独的MyCell.xib
中定义。 Interface Builder中单元的结构是非常标准的:
MyCell
SafeArea
ContentView
Container
Views, Labels, etc
我正在使用自动版式,对于Container
,水平约束是
Container.Leading = SuperView.Leading Margin
SuperView.Trailing Margin = Container.Trailing
这些边距由iOS自动计算,如我所见,例如对于iPhone 11 Pro,它们等于20,对于iPhone 5,它们等于8。一切看起来不错,表中的单元格具有不错的边距,我不想干扰表的外观。
现在我需要在屏幕上添加一个按钮,并且按钮的宽度必须等于表格单元格的宽度(即等于单元格Container
的宽度)。按钮在视图控制器中的层次结构与表在同一层次上(即按钮和表是同级的)。
问题是我需要在表格中填充单元格之前为按钮设置正确的宽度(它们是动态添加/从表格中删除的。)
我试图预加载单元格的xib并计算ContentView
的边距,但是当单元格追加到表时,边距发生了变化:
override func viewDidLoad() {
super.viewDidLoad()
let cell = Bundle.main.loadNibNamed(cellId, owner: nil, options: nil)?.first as! MyCell
cell.setNeedsLayout()
cell.layoutIfNeeded()
let leftMargin = cell.contentView.layoutMargins.left // = 8 <- incorrect
myButtonLeftMarginConstraint.constant = leftMargin
...稍后:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! MyCell
let leftMargin = cell.contentView.layoutMargins.left // = 20 <- correct value
myButtonLeftMarginConstraint.constant = leftMargin // too late, button already visible
所以问题是我如何才能提前知道在单元格实际添加到表之前,表单元格内容将使用什么边距(SuperView.Leading Margin
)。