UITableView旋转后滚动卡顿问题求助(titleForHeaderInSection相关)
问题解决方法
方案一:改用可复用的自定义Section Header
用viewForHeaderInSection替代titleForHeaderInSection,通过复用Header视图避免重复创建与计算,从根源减少卡顿:
class TableViewController: UITableViewController { private let headerIdentifier = "CustomHeader" init() { super.init(style: .insetGrouped) } required init?(coder: NSCoder) { super.init(coder: coder) } override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.description()) // 注册可复用的Header视图 tableView.register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: headerIdentifier) tableView.sectionHeaderHeight = UITableView.automaticDimension tableView.estimatedSectionHeaderHeight = 18 } override func numberOfSections(in tableView: UITableView) -> Int { 100 } // 替换默认标题方法,返回复用的Header视图 override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)! header.textLabel?.text = "Header" return header } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { tableView.dequeueReusableCell(withIdentifier: UITableViewCell.description(), for: indexPath) } }
方案二:固定Section Header高度(标题高度固定时适用)
如果标题文本、高度不会变化,直接设置明确的sectionHeaderHeight,避免系统反复计算高度,减少titleForHeaderInSection的调用频次:
override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.description()) // 替换自动高度为固定值,消除频繁计算 tableView.sectionHeaderHeight = 18 tableView.estimatedSectionHeaderHeight = 18 }
问题根源
当titleForHeaderInSection搭配UITableView.automaticDimension使用时,旋转屏幕后tableView会触发全局重布局。向上滚动时,系统需要为每个可见Section Header计算高度,但默认Header视图没有复用机制,会反复调用titleForHeaderInSection并创建临时视图进行高度计算,最终导致主线程阻塞、出现卡顿。
内容的提问来源于stack exchange,提问作者X.app
相关产品推荐
相关产品推荐

