SwiftUI视图左右存在额外空白问题求助
解决SwiftUI AddTodoView左右额外空白问题
你的AddTodoView中左右出现的额外空白,是因为Form控件默认继承了List的系统边距布局,下面提供两种实用的解决方式:
方法一:修改Form的列表样式
给Form添加.listStyle(.plain)修饰符,就能消除默认的左右边距,同时保留Form的原有功能:
struct AddTodoView: View { // MARK: - PROPERTIES @Environment(\.presentationMode) var presentationMode @State private var name: String = "" @State private var priority: String = "Normal" let priorities = ["High", "Normal", "Low"] var body: some View { NavigationView { VStack { Form { // MARK: - TODO NAME TextField("Todo", text: $name) // MARK: - TODO PRIORITY Picker("Priority", selection: $priority) { ForEach(priorities, id: \.self) { Text($0) } }.pickerStyle(SegmentedPickerStyle()) // MARK: - SAVE BUTTON Button(action: { print("save a new todo item") }) { Text("Save") } } //: FORM .listStyle(.plain) // 添加这一行消除默认边距 Spacer() } //: VSTACK .navigationBarTitle("New Todo", displayMode: .inline) .navigationBarItems(trailing: Button(action: { self.presentationMode.wrappedValue.dismiss() }) { Image(systemName: "xmark") } ) } // : NAVIGATION } }
方法二:自定义布局替代Form
如果需要完全控制界面边距和样式,可以用ScrollView+VStack替代Form,手动设置元素的边距:
struct AddTodoView: View { // MARK: - PROPERTIES @Environment(\.presentationMode) var presentationMode @State private var name: String = "" @State private var priority: String = "Normal" let priorities = ["High", "Normal", "Low"] var body: some View { NavigationView { ScrollView { VStack(spacing: 16) { // MARK: - TODO NAME TextField("Todo", text: $name) .padding(.horizontal) // MARK: - TODO PRIORITY Picker("Priority", selection: $priority) { ForEach(priorities, id: \.self) { Text($0) } } .pickerStyle(SegmentedPickerStyle()) .padding(.horizontal) // MARK: - SAVE BUTTON Button(action: { print("save a new todo item") }) { Text("Save") .frame(maxWidth: .infinity) .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } .padding(.horizontal) } .padding(.vertical) } //: SCROLLVIEW .navigationBarTitle("New Todo", displayMode: .inline) .navigationBarItems(trailing: Button(action: { self.presentationMode.wrappedValue.dismiss() }) { Image(systemName: "xmark") } ) } // : NAVIGATION } }
前者适合希望保留Form交互特性的场景,后者适合需要高度自定义界面的需求。
内容的提问来源于stack exchange,提问作者aws will
相关产品推荐
相关产品推荐

