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
相关产品推荐
相关产品推荐

