如何为SwiftUI List的两个Section设置特定间距?
SwiftUI List 两个Section设置特定间距的解决方案
你遇到的问题是\.defaultMinListHeaderHeight对小数值不生效,这是因为系统对这个环境值有最小限制,低于阈值的数值会被强制替换为系统默认的最小高度。下面提供两种可行的解决方法:
方法一:自定义Section的Footer/Header控制间距
给第一个Section添加一个透明的footer视图,直接设置想要的高度,精准控制两个Section之间的间距:
List { Section { Text("text 1") Text("text 2") } footer: { // 这里的height就是你想要的Section间距 Color.clear.frame(height: 5) } Section { Text("text 3") Text("text 4") } }
方法二:通过UITableView外观设置全局(需注意恢复)
利用UIKit的UITableView外观设置,直接修改Section的header高度,这种方法对小数值也能生效,但要记得在视图消失时恢复默认设置,避免影响其他List:
List { Section(header: Text("")) { Text("text 1") Text("text 2") } Section { Text("text 3") Text("text 4") } } .onAppear { UITableView.appearance().sectionHeaderHeight = 5 // 若不需要底部间距,可将footer高度设为0 UITableView.appearance().sectionFooterHeight = 0 } .onDisappear { // 恢复系统默认设置 UITableView.appearance().sectionHeaderHeight = UITableView.automaticDimension UITableView.appearance().sectionFooterHeight = UITableView.automaticDimension }
内容的提问来源于stack exchange,提问作者T33
相关产品推荐
相关产品推荐

