SwiftUI中如何移除Picker内边距并将隐藏标签的值左对齐?
最优解决方案
方案1:最简适配(推荐绝大多数场景)
Form 环境下隐藏标签的 Picker 被系统默认添加了8px的左内边距,直接用负边距抵消即可,改动量最小,兼容 iOS14 及以上版本:
import SwiftUI struct ContactFormView: View { var countries = ["Malaysia", "Singapore", "Japan"] @State var name: String = "" @State var mobile: String = "" @State var mobileCountry: String = "Malaysia" var body: some View { NavigationView { Form { Section(header: Text("Details")) { TextField("Name", text: $name) .border(Color.red, width: 1) HStack { Picker(selection: $mobileCountry, label: EmptyView()) { ForEach(countries, id: \.self) { Text($0) .frame(maxWidth: .infinity, alignment: .leading) .border(Color.red) } } .scaledToFit() .labelsHidden() .padding(.leading, -8) // 直接抵消系统默认8px左内边距 .border(Color.red, width: 1) TextField("Mobile", text: $mobile) .border(Color.red, width: 1) } } } .navigationBarTitle("New contact") } } }
方案2:完全自定义(适配性最强)
如果不想依赖系统固定的8px数值,避免后续系统版本样式调整导致对齐失效,可以用 Menu 自定义选择器替代系统 Picker,完全掌控布局边距,不存在系统默认内边距问题:
HStack { Menu { ForEach(countries, id: \.self) { country in Button(country) { mobileCountry = country } } } label: { Text(mobileCountry) .frame(maxWidth: .infinity, alignment: .leading) .border(Color.red) } .scaledToFit() .border(Color.red, width: 1) TextField("Mobile", text: $mobile) .border(Color.red, width: 1) }
内容的提问来源于stack exchange,提问作者Jon Saw
相关产品推荐
相关产品推荐

