UITableViewCell 高度估算
设备:iPhone XS Max, 系统:iOS 13.3
UITableView 自 iOS7.0开始,便默认开启 cell 高度估算机制,若想禁用,将属性estimatedRowHeight
设为0即可。
我们知道,如果 tableView 包含可变 cell 高度,加载 tableView 时,计算高度将会非常耗性能。而高度估算机制的出现,可以将这些耗时的计算从 tableView 加载时推迟到滚动时,从而提高了 tableView 的加载性能。
若关闭高度估算机制,每次调用reloadData
时:
- 首先会调用多次
heightForRowAtIndexPath:
(调用次数为 cell 总个数,即 numberOfSections * numberOfRows),从而确定contentSize
; - 其次,会调用
cellForRow
以及再次调用heightForRowAtIndexPath:
(调用次数为当前屏幕需要展示的 cell 个数)。
然而,如果开启高度计算时,系统并不会预先调用多次heightForRowAtIndexPath:
,而是在调用完cellForRow
后,紧接着调用heightForRowAtIndexPath:
来确定contentSize
。
当 tableView 首次出现在屏幕上时,系统只会调用 m 次 cellForRow
和heightForRowAtIndexPath:
,之后,再在滚动过程中,不断的修正contentSize
大小。
而这个次数 m 计算如下:
m = tableViewHeight / estimatedRowHeight. (number of rows >= m >= visible rows)