【发布时间】:2018-04-23 12:44:00
【问题描述】:
我有一个 UITableView 并在其中包含单元格,我在其中使用 textLabel 和 detailTextLabel 以及作为公开指示符的附件视图。这些是我的限制。
if (cell.contentView.constraints.count == 0) {
cell.textLabel?.translatesAutoresizingMaskIntoConstraints = false
cell.detailTextLabel?.translatesAutoresizingMaskIntoConstraints = false
let margins = cell.contentView.layoutMarginsGuide
// TextLabel constraints
cell.textLabel?.leftAnchor.constraint(equalTo: margins.leftAnchor).isActive = true
cell.textLabel?.centerYAnchor.constraint(equalTo: margins.centerYAnchor).isActive = true
// DetailTextLabel constraints
cell.detailTextLabel?.rightAnchor.constraint(equalTo: margins.rightAnchor, constant: -10).isActive = true
cell.detailTextLabel?.leftAnchor.constraint(equalTo: (cell.textLabel?.layoutMarginsGuide.rightAnchor)!, constant: 10).isActive = true
cell.detailTextLabel?.centerYAnchor.constraint(equalTo: margins.centerYAnchor).isActive = true
}
现在,当第一次加载表格视图时,我看到一切正常,即 detailTextLabel 距离 contentView -10 点,但是当我点击单元格时,detailTextLabel 向右移动并拥抱 contentView,就好像 - 10点约束甚至不存在。现在当我再次回到这个 VC 时,我仍然看到 detailTextLabel 拥抱 contentView 即 reloadData 没有任何效果。但是,如果我解雇了这个 VC 并再次回到这里,我的约束和它们应该在的位置,当我点击单元格进入下一个屏幕时问题再次出现。
我的 viewWillAppear 中有一个 reloadData() 调用,它被调用但没有产生任何效果。
我希望我能解释一下自己,我在这里做错了吗?
【问题讨论】:
-
你能在
cellForRowAt中试试cell.contentView.layoutIfNeeded()吗? -
检查在 if 语句中设置了多少次约束,每行一次还是被多次调用?
-
为什么在设置约束之前要检查是否有零约束?有实际需要吗?如果没有看到比发布更多的代码,我强烈怀疑 if 语句是罪魁祸首,删除它会解决问题。
标签: ios swift uitableview autolayout