嵌入ViewController的TableViewCell与安全区间的空白间隙如何删除
消除TableViewCell与安全区间空白的解决方案
你可以按以下优先级排查修改:
- 关闭UIScrollView自动内边距调整
iOS 11及以上系统默认会根据安全区自动调整TableView的内容内边距,在ViewController的viewDidLoad方法中添加代码关闭该特性:
Swift版本:
Objective-C版本:tableView.contentInsetAdjustmentBehavior = .neverself.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; - 修正TableView约束
检查Storyboard/Xib或者手写代码中TableView的四边约束,确保leading、trailing、top、bottom四个约束是关联到ViewController父视图的边缘,而非父视图的安全区,让TableView撑满整个屏幕区域。 - 重置分隔符边距
如果使用系统默认的Cell分隔符,默认左侧保留16pt边距,可通过全局配置重置:tableView.separatorInset = .zero tableView.separatorStyle = .singleLine - 调整自定义Cell内部约束
自定义Cell内的背景视图、内容控件需要直接约束到contentView的四边,不要约束到contentView的layoutMargins或者安全区,同时添加代码关闭边距继承:cell.contentView.preservesSuperviewLayoutMargins = false cell.contentView.layoutMargins = .zero - 消除Section默认间距
iOS 15及以上系统默认给Section头部增加了顶部padding,不需要的话可以全局关闭:
如果不需要Section的头部、尾部视图,可将对应高度设置为极小值消除空白:if #available(iOS 15.0, *) { tableView.sectionHeaderTopPadding = 0 }func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude }
内容的提问来源于stack exchange,提问作者Juan Camilo Rodrigez
相关产品推荐
相关产品推荐

