如何在 SwiftUI 中删除带有隐藏标签的 Padding/Align 选择器值?

How to Remove Padding/Align Picker Value Left with Hidden Label in SwiftUI?

我正在尝试将我的 Picker 隐藏标签值与表单中的另一个 TextField 对齐 (see attached image)。删除显示的选择器值中的 8px 填充的最佳方法是什么?

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([=11=]).border(Color.red)
              }
            }
              .scaledToFit()
              .labelsHidden()
              .border(Color.red, width: 1)
            TextField("Mobile", text: $mobile)
              .border(Color.red, width: 1)
          }
        }
      }
      .navigationBarTitle("New contact")
    }
  }
}

最好的选择可能是在选择器上使用负填充:

Picker(selection: $mobileCountry, label: EmptyView()) {
              ForEach(countries, id: \.self) {
                Text([=10=]).border(Color.red)
              }
            }
              .scaledToFit()
              .labelsHidden()
              .border(Color.red, width: 1)
              .padding(.horizontal, -8)

在 Xcode 12.5 中加载您的代码,添加负填充以您想要的方式对齐文本。

直觉上我会选择 .padding(.leading, -8) 仅删除选择器前缘的填充 - 但这样做时,选择器和文本字段之间的间隙会变大。

对两个水平值应用负填充使我的差距保持不变。但我建议在您的代码中同时尝试这两种方法,然后看看哪一种对您最有意义。