SwiftUI List自动为内部元素添加额外边距,如何移除?
解决SwiftUI Grouped List中自定义View的额外边距问题
我开发简易待办清单App时遇到个问题:自定义的TestView单独预览显示正常,但放进设置为.grouped样式的List后,日历图标和底部行出现了额外边距。
问题代码回顾
单独预览正常的TestView:
struct TestView: View { var body: some View { VStack(alignment: .leading) { Text("Wash the laundry") .font(.headline) Spacer() HStack { Label("9 days ago", systemImage: "calendar") Spacer() Label("No assignee", systemImage: "person.fill") .labelStyle(.trailingIcon) .foregroundColor(.gray) } .font(.caption) } .padding() } }
放入Grouped List后的代码:
struct TestListView: View { var body: some View { NavigationView { List { TestView() } .navigationTitle("All Tasks") .listStyle(.grouped) } } }
解决办法
给TestView添加.listRowInsets(EdgeInsets())修饰符,直接移除List行的默认内边距:
struct TestListView: View { var body: some View { NavigationView { List { TestView() .listRowInsets(EdgeInsets()) } .navigationTitle("All Tasks") .listStyle(.grouped) } } }
如果需要保留部分内边距(比如左右留16pt),可以自定义Insets数值:
.listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
原因说明
.grouped样式的List默认会给每个行元素添加固定内边距,和TestView自身的.padding()叠加后,就出现了多余的空白边距。通过.listRowInsets重置行内边距,就能让自定义View的布局和单独预览时保持一致。
内容的提问来源于stack exchange,提问作者jayjyli
相关产品推荐
相关产品推荐

