如何为Form中展开的DisclosureGroup添加底部间距?
解决SwiftUI Form中DisclosureGroup展开后底部间距问题
以下是几种无需手动重复编写Section的编程实现方案:
方案1:利用Section自动适配间距
直接将每个DisclosureGroup包裹在Section中,借助Form里Section的原生间距特性,自动实现展开状态下的底部间距效果,代码简洁且贴合SwiftUI原生样式规范:
struct ContentView: View { let serviceGroups = ["Group 1", "Group 2", "Group 3"] let services = ["Service A", "Service B", "Service C"] var body: some View { NavigationView { Form { ForEach(serviceGroups, id: \.self) { serviceGroup in Section { DisclosureGroup(serviceGroup) { ForEach(services, id: \.self) { service in VStack(alignment: .leading, spacing: 4) { Text(service) HStack { Text("$400") Text("1 h. 30 min.") }.font(.subheadline) .foregroundColor(.secondary) } } } } } } } } }
方案2:绑定展开状态动态添加间距
通过记录每个DisclosureGroup的展开状态,动态为底部添加padding,适合需要自定义间距大小的场景:
struct ContentView: View { let serviceGroups = ["Group 1", "Group 2", "Group 3"] let services = ["Service A", "Service B", "Service C"] @State private var expandedStates: [Bool] = [] var body: some View { NavigationView { Form { ForEach(serviceGroups.indices, id: \.self) { index in DisclosureGroup(serviceGroups[index], isExpanded: $expandedStates[index]) { ForEach(services, id: \.self) { service in VStack(alignment: .leading, spacing: 4) { Text(service) HStack { Text("$400") Text("1 h. 30 min.") }.font(.subheadline) .foregroundColor(.secondary) } } } .padding(.bottom, expandedStates[index] ? 16 : 0) } } .onAppear { expandedStates = Array(repeating: false, count: serviceGroups.count) } } } }
方案3:自定义DisclosureGroup样式
如果需要高度定制化的样式逻辑,可以自定义DisclosureGroupStyle,在样式中处理展开状态的间距:
struct SpacingDisclosureGroupStyle: DisclosureGroupStyle { func makeBody(configuration: Configuration) -> some View { VStack(alignment: .leading, spacing: 0) { configuration.label .onTapGesture { configuration.isExpanded.toggle() } if configuration.isExpanded { configuration.content .padding(.top, 8) } } .padding(.bottom, configuration.isExpanded ? 16 : 0) } } // 使用示例 struct ContentView: View { let serviceGroups = ["Group 1", "Group 2", "Group 3"] let services = ["Service A", "Service B", "Service C"] var body: some View { NavigationView { Form { ForEach(serviceGroups, id: \.self) { serviceGroup in DisclosureGroup(serviceGroup) { ForEach(services, id: \.self) { service in VStack(alignment: .leading, spacing: 4) { Text(service) HStack { Text("$400") Text("1 h. 30 min.") }.font(.subheadline) .foregroundColor(.secondary) } } } .disclosureGroupStyle(SpacingDisclosureGroupStyle()) } } } } }
内容的提问来源于stack exchange,提问作者Roman Mahotskyi
相关产品推荐
相关产品推荐

