如何在navigationBar与首个UITableViewCell之间添加间距?
嘿,这个需求我碰到过好多次,其实有几种实用的方案,你可以根据自己的场景来选:
方案一:使用tableHeaderView(最推荐)
这是最直接且无副作用的方法,相当于给表格顶部加了一个空白的头部视图,完全不影响cell的复用和滚动逻辑。
如果你用代码创建tableView,直接这么写:
// 自定义你需要的间距高度,比如20pt let spacingHeight: CGFloat = 20 let spacingView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: spacingHeight)) // 把背景色设成和tableView一致,避免出现突兀的色块 spacingView.backgroundColor = tableView.backgroundColor tableView.tableHeaderView = spacingView
如果是用自动布局(推荐适配不同屏幕),记得加上这些步骤:
let spacingView = UIView() spacingView.translatesAutoresizingMaskIntoConstraints = false // 固定高度约束 spacingView.heightAnchor.constraint(equalToConstant: 20).isActive = true tableView.tableHeaderView = spacingView // 手动触发尺寸适配,不然自动布局可能不生效 tableView.tableHeaderView?.sizeToFit()
方案二:调整contentInset(适合滚动联动场景)
如果你希望这个间距能跟着表格一起滚动(比如下拉刷新时间距也会往上移),可以调整tableView的内容内边距:
let additionalSpacing: CGFloat = 20 // 注意要叠加系统默认的内边距(比如safeArea或导航栏带来的偏移) let newTopInset = tableView.adjustedContentInset.top + additionalSpacing tableView.contentInset = UIEdgeInsets( top: newTopInset, left: tableView.contentInset.left, bottom: tableView.contentInset.bottom, right: tableView.contentInset.right )
⚠️ 注意:这个方法会让整个表格内容下移,包括表头和所有cell,如果你不需要滚动时间距跟着动,优先选方案一。
方案三:利用Section Header(多section场景适用)
如果你的tableView本身就分section,给第一个section设置空白header也是个不错的选择:
// 设置section header高度 func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? 20 : 0 // 第一个section留20pt间距,其他section无间距 } // 返回空白header视图 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard section == 0 else { return nil } let headerView = UIView() headerView.backgroundColor = tableView.backgroundColor return headerView }
避坑提醒
- 不要直接修改第一个cell的top约束!cell是复用的,这么做会导致后续复用的cell也出现奇怪的间距。
- 如果导航栏是半透明的,记得考虑
safeAreaInsets的影响,方案一和方案二都已经帮你处理了这个问题。
内容的提问来源于stack exchange,提问作者iX0ness
相关产品推荐
相关产品推荐

