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

如何为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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 18:45:09