UITableViewCell布局在单元被重用之前不会更新 [英] UITableViewCell layout not updating until cell is reused
问题描述
我有一个自动填充单元格大小的UITableView.
UITableView
设置非常简单:
I have a UITableView that I fill with autosizing cells.
UITableView
setup is fairly simple:
tableView.estimatedRowHeight = 70
tableView.rowHeight = UITableViewAutomaticDimension
与Apple完全相同,建议在这里进行以下操作: https ://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithSelf-SizingTableViewCells.html
Exactly like Apple recommends here: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithSelf-SizingTableViewCells.html
要启用自动调整大小的表格视图单元格,您必须将表格视图的 UITableViewAutomaticDimension的rowHeight属性.你还必须 将一个值分配给estimateRowHeight属性.两者都 设置这些属性后,系统将使用自动布局"来计算 行的实际高度.
To enable self-sizing table view cells, you must set the table view’s rowHeight property to UITableViewAutomaticDimension. You must also assign a value to the estimatedRowHeight property. As soon as both of these properties are set, the system uses Auto Layout to calculate the row’s actual height.
在配置单元格时,我还禁用/启用了一些约束以实现所需的外观.那就是事情变得有趣的地方.在重新使用单元之前,单元布局不会更新.字面上地.您可以调用layoutIfNeeded()
,setNeedsLayout()
,layoutSubviews()
或任何其他方法,无法强制单元更新其布局.
When configuring a cell I also disable/enable some constraints to achieve the needed look. That’s where things get interesting. Cell layout is not updated until the cell is reused. Literally. You can call layoutIfNeeded()
, setNeedsLayout()
, layoutSubviews()
or any other method there is, there is no way you will force the cell to update its layout.
所有其他方面的效果都很好:标签确实可以更改其文本,您可以隐藏/取消隐藏视图,但是布局会一直停留到重新使用单元格为止.
All other aspects work pretty good: labels do change their text, you hide/unhide the views, but layout is stuck until the cell is reused.
问题:是什么原因引起的,以及如何避免这种行为?
Question: what causes it and how to avoid this behavior?
推荐答案
我也遇到了您的问题.而不是删除
I had your problem too. Instead of remove
tableView.estimatedRowHeight = 70
我刚刚在返回单元格本身之前,在cellForRow方法的末尾添加了一个layoutIfNeeded:
I just added a layoutIfNeeded at the end of the cellForRow method, just before return the cell itself:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as? MyCustomCell
...
cell?.layoutIfNeeded()
return cell!
}
结果:第一次,每次重复使用后,单元布局始终是完美的.
Result: the cell layout is perfect always, the first time and every after reuse.
这篇关于UITableViewCell布局在单元被重用之前不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!