tableView.estimatedRowHeight = 70
tableView.rowHeight = UITableViewAutomaticDimension
像Apple在这里的建议一样:
https://develveper.com/library/content/content/documentation/userexperience/coneptual/coneptual/autolayoutpg/workingwith selfsizingwithelfssizingtableviewcells.html
要启用自我尺寸的表观视图单元格,您必须设置表观 rowheight属性到UITATIONVIEWAUTOMANICDIMENY。你也必须 为估算的属性分配值。一旦两个 设置了这些属性,系统使用自动布局来计算 行的实际高度
配置单元格时,我还禁用/启用一些约束以实现所需的外观。那就是事情变得有趣的地方。在重复使用单元格之前,不会更新单元格的布局。字面上地。您可以调用layoutIfNeeded()
或任何其他方法,您无法强迫单元格更新其布局。setNeedsLayout()
,
layoutSubviews()
其他方面都很好:标签确实更改文本,您隐藏/删除视图,但是布局被卡住直到重复使用。
问题:是什么原因导致它,以及如何避免这种行为?我也有你的问题。而不是删除
tableView.estimatedRowHeight = 70
I刚刚在cellforrow方法的末尾添加了一个布局,就在返回单元本身之前:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as? MyCustomCell
...
cell?.layoutIfNeeded()
return cell!
}
不幸的是,没有提供的答案/评论为我解决。我总是以最初的不正确布局。仅在重复使用单元格或调用
reloadData()
(在表视图上)才能正确显示。以下是唯一对我有用的事情。我不是这样的骇客粉丝,但是在这个看似非常简单的布局问题上花了大约半天的时间之后,我就放弃了。 >
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
在线,您也可以将其调用
reloadData
(没有hack),但是当布局从“错误”跳到“正确”时,您可以清楚地看到“跳跃”。 nyway,只是想分享我的经验,并希望这对别人有所帮助。欢呼!
在重复使用单元格之前,不会更新细胞布局
如果您希望TableView反映更改的单元格。 <
更改单元格布局并重新绘制表查看viewDidAppear
例如:
DispatchQueue
在我的案子中,问题是由 tableView.beginUpdates()
tableView.setNeedsDisplay()
tableView.endUpdates()
引起的。
simply删除这条线 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? CustomCell else { return }
cell.collapseDescriptionLabel()
// redraw the tableView
tableView.beginUpdates()
tableView.setNeedsDisplay()
tableView.endUpdates()
}
弄脏了我的问题。单元格正确地更新了其布局,几乎解决了我的问题。 ,但很可能,您将遇到另一个麻烦,而细胞的高度设置为43.5分。您的日志还将充满自动布局错误,其中包括这样的行
estimatedRowHeight
明显地,如果您不提供
tableView.estimatedRowHeight = 70
如何避免该错误?我还不知道。 我发布了一个问题,一旦找到答案,我将在此问题中提供链接。
您不需要使用
<NSLayoutConstraint:0x600000097570 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fd4ee511d20.height == 43.5 (active)>
,layoutIfNeeded()
来强制布局。您可以使用
setNeedsLayout()
和layoutSubviews()
例如:
tableView.beginUpdates()
我正面临与OP相同的情况,我还在我的
tableView.endUpdates()
中使用自我尺寸。
下面的步骤为我解决了问题: -
这两条线: -func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
tableView.beginUpdates()
cell.heightConstraint.constant = 50
tableView.endUpdates()
}
后
UITableViewCell
致电UITableView
: - tableView.estimatedRowHeight = 70
tableView.rowHeight = UITableViewAutomaticDimension
: - reloadData()