iOS 14下如何移除GroupedListStyle列表分组上方的空白区域?
解决GroupedListStyle分组无头部时的空白问题
针对iOS 14/15和iOS 16+的系统差异,可通过以下几种方式消除分组上方的空白区域:
方法1:用EmptyView替代默认头部
直接给Section的header设置EmptyView(),能大幅缩减默认空白,是最基础的调整方式:
List { Section(header: EmptyView()) { Text("List 1 - Item 1") Text("List 1 - Item 2") Text("List 1 - Item 3") } Section(header: EmptyView()) { Text("List 2 - Item 1") Text("List 2 - Item 2") Text("List 2 - Item 3") } } .listStyle(.grouped)
方法2:版本适配的内边距调整
利用系统版本判断,针对不同iOS版本设置对应的内边距,同时注意恢复默认样式避免影响其他页面:
List { Section(header: EmptyView()) { Text("List 1 - Item 1") Text("List 1 - Item 2") Text("List 1 - Item 3") } Section(header: EmptyView()) { Text("List 2 - Item 1") Text("List 2 - Item 2") Text("List 2 - Item 3") } } .listStyle(.grouped) .padding(.top, -35) // iOS 16+ 生效 .onAppear { if #available(iOS 15, *) {} else { // iOS 14 调整列表全局内边距 UITableView.appearance().contentInset.top = -35 } } .onDisappear { // 离开页面后恢复默认设置 if #available(iOS 15, *) {} else { UITableView.appearance().contentInset.top = 0 } }
方法3:自定义ListStyle(跨版本统一效果)
如果需要完全控制分组样式,可自定义ListStyle,彻底消除空白并保持和系统分组风格一致:
struct NoHeaderGroupedListStyle: ListStyle { func makeBody(configuration: Configuration) -> some View { ScrollView { VStack(spacing: 0) { ForEach(configuration.sections) { section in VStack(spacing: 0) { // 隐藏并压缩header高度 section.header .frame(height: 0) .hidden() ForEach(section.items) { item in item .listRowSeparator(.visible) } } .background(Color(.systemBackground)) .cornerRadius(10) .padding(.horizontal) .padding(.bottom, 8) } } .padding(.top, 8) } } } // 使用自定义样式 List { Section { Text("List 1 - Item 1") Text("List 1 - Item 2") Text("List 1 - Item 3") } Section { Text("List 2 - Item 1") Text("List 2 - Item 2") Text("List 2 - Item 3") } } .listStyle(NoHeaderGroupedListStyle())
内容的提问来源于stack exchange,提问作者iroh
相关产品推荐
相关产品推荐

