如何在 SwiftUI 中删除填充/将选取器值与隐藏标签左侧对齐?

Jon*_*Saw 2 swiftui swiftui-picker

我正在尝试将我的隐藏标签值与表单中的Picker另一个值对齐(请参阅附图)。删除显示的选择器值中的填充的最佳方法是什么?TextField8px

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).border(Color.red)
              }
            }
              .scaledToFit()
              .labelsHidden()
              .border(Color.red, width: 1)
            TextField("Mobile", text: $mobile)
              .border(Color.red, width: 1)
          }
        }
      }
      .navigationBarTitle("New contact")
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

左对齐选取器值

Sco*_*man 7

也许你最好的选择是在选择器上使用负填充:

\n
Picker(selection: $mobileCountry, label: EmptyView()) {\n              ForEach(countries, id: \\.self) {\n                Text($0).border(Color.red)\n              }\n            }\n              .scaledToFit()\n              .labelsHidden()\n              .border(Color.red, width: 1)\n              .padding(.horizontal, -8)\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

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

\n

对两个水平值应用负填充可以使间隙对我来说保持不变。但我建议在您的代码中尝试两种方法,看看哪一种对您最有意义。

\n