SwiftUI列表:如何将两个Section间距缩小至16px
解决SwiftUI列表Section间距过大问题
需求与问题
要让SwiftUI列表中的两个Section保持独立,但间距缩小至约16px,同时保留默认列表样式。之前尝试的两种方案都存在问题:
- 使用
.listRowInsets(EdgeInsets())导致GoPremium按钮的图片被截断,显示异常 - 将GoPremium移到List外的VStack中,背景与列表不匹配,设置frame也无法调整到合适宽度
解决方案
方案1:调整Section间距(推荐)
通过修改UITableView的外观属性,精准控制Section之间的间距,同时不影响列表默认样式。在SettingsView的List中添加onAppear和onDisappear临时修改全局设置,避免影响其他页面:
struct SettingsView: View { @State var pageSelected: String? @State var pages: [String] = ["Add your own", "Notifications", "About", "Instagram", "Twitter", "Email", "Terms of Service", "Privacy Policy"] var footer: some View { Text("footer") .font(.body).fontWeight(.bold) .foregroundColor(.black) .frame(maxHeight: .infinity, alignment: .bottom) .padding(.bottom) } var body: some View { List { Section { GoPremium() } ForEach(pages, id: \.self) { item in Button { self.pageSelected = item } label: { Text(item) .font(.callout).fontWeight(.semibold) .foregroundColor(.black) } } } .onAppear { // 设置Section之间的间距为16px UITableView.appearance().sectionFooterHeight = 16 } .onDisappear { // 恢复默认间距设置 UITableView.appearance().sectionFooterHeight = UITableView.automaticDimension } .scrollDisabled(true) .navigationBarBackButtonHidden(true) .navigationBarTitle("Settings", displayMode: .large) .navigationBarItems(leading: BackButton()) .overlay(footer) } }
方案2:自定义Section Footer控制间距
如果不想修改全局UITableView设置,可以给第一个Section添加自定义Footer,手动控制间距:
List { // 第一个Section,用空视图作为Footer设置间距 Section(footer: Color.clear.frame(height: 16)) { GoPremium() } .environment(\.defaultMinListFooterHeight, 0) // 去掉默认Footer高度 // 第二个Section,去掉默认Header高度 Section { ForEach(pages, id: \.self) { item in Button { self.pageSelected = item } label: { Text(item) .font(.callout).fontWeight(.semibold) .foregroundColor(.black) } } } .environment(\.defaultMinListHeaderHeight, 0) }
修复GoPremium布局问题
之前的图片截断是因为缺少固定高度和裁剪,修改GoPremium代码:
struct GoPremium: View { var body: some View { VStack(spacing: 7) { Button { } label: { Image("goPremium") .resizable() .aspectRatio(contentMode: .fill) .frame(height: 120) // 固定图片高度 .overlay( VStack(alignment: .leading, spacing: 12) { Text("Go Premium") .font(.title2).fontWeight(.bold) Text("Access all **********, ******, *****, and remove ads!") .multilineTextAlignment(.leading) .shadow(radius: 1, x: 0, y: 3) } .padding() .foregroundColor(.white)) .clipped() // 裁剪超出范围的图片 } .cornerRadius(12) .shadow(radius: 3, x: 0, y: 5) } .padding(.horizontal) // 保留水平内边距,匹配列表默认样式 } }
这样修改后,两个Section的间距会缩小到16px,同时GoPremium按钮显示正常,列表也保留了默认样式。
内容的提问来源于stack exchange,提问作者ducling
相关产品推荐
相关产品推荐

