iOS 表格视图的行高计算与选择处理
1. 可变行高的计算方法
1.1 预估行高法
为了减少初始时计算行高的时间,可以提供一个预估行高。当在表格显示前多次调用 tableView(_:heightForRowAt:)
时,仅对可见单元格调用该方法,其余单元格使用预估高度。这样运行时能快速获取足够信息来布局整个表格,只需提前提供初始可见行的实际高度。不过,这种布局只是近似值,后续需要修正。当新行滚动到视图中时,会再次调用 tableView(_:heightForRowAt:)
来修正布局。
以下是设置预估行高和实现 tableView(_:heightForRowAt:)
的示例代码:
// 在 viewDidLoad 中设置预估行高
self.tableView.estimatedRowHeight = 75
override func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
let ix = indexPath.row
if self.rowHeights[ix] == nil {
let objects = UINib(nibName: "MyCell", bundle: nil)
.instantiate(withOwner: nil)
let