如何调整UITableView高度使选中的section header滚动至顶部固定

实现UITableView指定section header滚动到顶部的方案
不需要修改UITableView本身的高度,直接调用系统自带API即可实现需求,不同场景对应不同实现方式:
常规场景:目标section存在至少1行cell
直接滚动到该section的第0行,指定滚动位置为顶部即可:// Swift 示例 let targetSection = 1 // 替换为你的目标section序号 let indexPath = IndexPath(row: 0, section: targetSection) tableView.scrollToRow(at: indexPath, at: .top, animated: true)// Objective-C 示例 NSInteger targetSection = 1; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:targetSection]; [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];滚动后header被导航栏遮挡的适配
如果滚动后header停在导航栏下方,需要调整tableView的contentInset避开导航栏高度:// 适配导航栏不透明的场景 let topInset = (navigationController?.navigationBar.bounds.height ?? 0) + UIApplication.shared.statusBarFrame.height tableView.contentInset = UIEdgeInsets(top: topInset, left: 0, bottom: 0, right: 0)特殊场景:目标section没有任何cell
直接获取section header的frame,手动设置tableView的偏移量:let targetSection = 1 let headerFrame = tableView.rectForHeader(inSection: targetSection) tableView.setContentOffset(CGPoint(x: 0, y: headerFrame.minY - tableView.contentInset.top), animated: true)
内容的提问来源于stack exchange,提问作者Alex Bro
相关产品推荐
相关产品推荐

