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

SwiftUI中如何移除列表Section间空白?iOS16适配问题

在SwiftUI iOS 16+ 中移除List Section间空白的解决方法

方法一:调整Section Footer并保留全局外观设置

iOS 16起,EmptyView作为Section Footer不再能覆盖默认的空白高度,你需要把EmptyView替换为一个高度强制为0的透明视图,同时保留原来的全局TableView设置:

init() {
    // 全局设置Section Footer高度
    UITableView.appearance().sectionFooterHeight = 0
}

var body: some View {
    List {
        ForEach(servicesEnv.dictionary.keys.sorted(), id: \.self) { key in
            Section(
                header: SectionHeader(sectionName: "\(key)"),
                footer: Color.clear.frame(height: 0) // 替代EmptyView
            ) {
                MyView()
            }
        }
    }
    .listStyle(GroupedListStyle())
}

方法二:使用iOS 16+ 原生修饰符(更推荐)

iOS 16新增了.listSectionSpacing(_:)修饰符,可以直接控制Section之间的间距,无需依赖UIKit的外观设置:

List {
    ForEach(servicesEnv.dictionary.keys.sorted(), id: \.self) { key in
        Section(
            header: SectionHeader(sectionName: "\(key)"),
            footer: EmptyView()
        ) {
            MyView()
        }
    }
}
.listStyle(GroupedListStyle())
.listSectionSpacing(0) // 直接设置Section间距为0

为什么原来的方法失效?

iOS 16对GroupedListStyle的布局逻辑做了调整,EmptyView作为Footer时,系统仍会保留默认的最小空白高度;而设置高度为0的透明视图可以强制Footer高度归零,配合全局外观设置就能完全移除Section间的空白。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:30:39