You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UITableView无section头部和尾部的区域出现多余间隙该如何消除

解决方案

你遇到的是UITableView在grouped样式下的系统默认额外间距问题,以及iOS15新增的头部默认padding导致的问题,按以下步骤修改即可:

步骤1:设置UITableView全局默认头脚高度

grouped样式的UITableView有全局默认的最小头脚间距,仅针对单个section返回0高度不会生效,需要在tableView初始化时添加以下配置:

tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = CGFloat.leastNormalMagnitude
tableView.sectionFooterHeight = UITableView.automaticDimension
tableView.estimatedSectionFooterHeight = CGFloat.leastNormalMagnitude

步骤2:适配iOS15及以上系统的头部默认padding

iOS15新增了sectionHeaderTopPadding属性,默认值为22,会给所有section头部增加额外间距,添加以下代码关闭默认padding:

if #available(iOS 15.0, *) {
    tableView.sectionHeaderTopPadding = 0
}

步骤3:修改头脚高度代理的返回值

系统在部分版本中会忽略头脚高度代理返回的0.0,自动替换为默认的最小间距,把你代理中不需要显示头脚时的返回值从0.0改为CGFloat.leastNormalMagnitude即可,示例如下:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if sections[section].showSectionHeader {
        return 50.0
    }
    return CGFloat.leastNormalMagnitude
}

// footer高度的代理同理修改,不需要显示时返回CGFloat.leastNormalMagnitude

完成以上三步后多余的间隙即可消失。

内容的提问来源于stack exchange,提问作者Stephan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:15:03