iOS 15环境下SwiftUI List Section头部固定内边距无法自定义问题
iOS 15 及以上版本使用 PlainListStyle 时,SwiftUI 会给 Section 的头部、尾部视图默认添加系统级的列表行内边距,该内边距不属于自定义的头部视图本身,而是 List 对 Section 容器默认施加的布局约束,因此直接给自定义头部加padding、设置defaultMinListHeaderHeight都无法生效。
解决方法1:局部修改单个Section头部边距
给自定义的header内容添加.listRowInsets修饰符,将默认行边距置零即可,修改后的代码如下:
List { Section(header: Text("Big header") .foregroundColor(.red) .background(Color.gray) .frame(height: 30) // 关键:清空当前行的默认内边距 .listRowInsets(EdgeInsets()) ) { Text("Hello, world! 1") .padding() Text("Hello, world! 2") .padding() Text("Hello, world! 3") .padding() } } .environment(\.defaultMinListHeaderHeight, 1) .listStyle(PlainListStyle())
如果需要自定义边距,直接在EdgeInsets里设置对应数值即可,示例:.listRowInsets(.init(top: 0, leading: 10, bottom: 0, trailing: 10))。
解决方法2:全局修改所有List的Section头部边距
如果需要全局生效,可以在App启动时配置UITableView的全局外观:
// 在App入口的init方法或者UIApplication didFinishLaunchingWithOptions回调中添加 UITableView.appearance().sectionHeaderTopPadding = 0 // 清空头部容器默认内边距 UITableViewHeaderFooterView.appearance().contentView.preservesSuperviewLayoutMargins = false UITableViewHeaderFooterView.appearance().contentView.layoutMargins = .zero
该方法会对App内所有使用PlainListStyle的List生效,不需要单独给每个Section加修饰符。
两种方案都可以完全移除默认的左右20px、上下6px多余内边距,自定义头部视图可完全撑满Section头部容器,自定义高度也不会受系统默认最小高度限制。
内容的提问来源于stack exchange,提问作者kcome
相关产品推荐
相关产品推荐

