【问题标题】:How to Remove Padding/Align Picker Value Left with Hidden Label in SwiftUI?如何在 SwiftUI 中使用隐藏标签删除填充/对齐选择器值?
【发布时间】:2021-05-06 05:23:14
【问题描述】:

我正在尝试将我的 Picker 隐藏标签值与我的表单 (see attached image) 中的另一个 TextField 对齐。在显示的选择器值中删除 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($0).border(Color.red)
              }
            }
              .scaledToFit()
              .labelsHidden()
              .border(Color.red, width: 1)
            TextField("Mobile", text: $mobile)
              .border(Color.red, width: 1)
          }
        }
      }
      .navigationBarTitle("New contact")
    }
  }
}

【问题讨论】:

    标签: swiftui swiftui-picker


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多