如何在 SwiftUI 中设置 TextField 的键盘类型?

How to set Keyboard type of TextField in SwiftUI?

我似乎找不到任何信息或弄清楚如何在 Swift 的 TextField 上设置键盘类型UI。 能够启用安全文本 属性、隐藏密码等也很好

此 post 展示了如何 "wrap" 一个 UITextField,但如果不需要,我宁愿不使用任何 UI 控件。

有人知道如何在不包装旧学校 UI 控件的情况下完成此操作吗?

I'm the dev that answered that post - there's no official way to do so at the moment. Your best bet at the moment is to wrap UITextField – Matteo Pacini

综上所述,我猜我们暂时无法包装 UITextField。

要创建一个可以输入安全文本的字段,您可以使用 SecureField($password)

https://developer.apple.com/documentation/swiftui/securefield

如果您想将文本字段的 contentType 设置为例如。 .oneTimeCode 你可以这样做。也适用于 keyboardType

TextField($code)
    .textContentType(.oneTimeCode)
    .keyboardType(.numberPad)

下面使用 UIViewRepresentable 包装了一个名为 UIKitTextFieldUITextField class。键盘类型设置为 .decimalPad,但可以设置为任何有效的键盘类型。

//  UIKitTextField.swift

import UIKit

class UIKitTextField: UITextField, UITextFieldDelegate {

  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    delegate = self
  }

  required override init(frame: CGRect) {
    super.init(frame: frame)
    delegate = self
    self.setContentHuggingPriority(.defaultHigh, for: .vertical)
  }
}

ContentView.Swift我创建了两个TextFields。第一个是包装 UIKit UITextField,第二个是 SwiftUI TextField。数据绑定相同,因此每个都将显示与输入时相同的文本。

// ContentView.Swift

import SwiftUI
import UIKit

struct MyTextField : UIViewRepresentable {

  @Binding var myText: String

  func makeCoordinator() -> MyTextField.Coordinator {
    return Coordinator(text: $myText)
  }

  class Coordinator: NSObject {
    @Binding var text: String
    init(text: Binding<String>) {
      $text = text
    }

    @objc func textFieldEditingChanged(_ sender: UIKitTextField) {
      self.text = sender.text ?? ""
    }
  }

  func makeUIView(context: Context) -> UIKitTextField {

    let myTextField = UIKitTextField(frame: .zero)

    myTextField.addTarget(context.coordinator, action: #selector(Coordinator.textFieldEditingChanged(_:)), for: .editingChanged)

    myTextField.text = self.myText
    myTextField.placeholder = "placeholder"
    myTextField.borderStyle = .roundedRect
    myTextField.keyboardType = .decimalPad

    return myTextField
  }

  func updateUIView(_ uiView: UIKitTextField,
                    context: Context) {
    uiView.text = self.myText
  }

}


struct MyTextFieldView: View {
  @State var myText: String = "Test"
  var body: some View {
    VStack {
      MyTextField(myText: $myText)
        .padding()
      TextField($myText)
        .textFieldStyle(.roundedBorder)
        .padding()
    }
  }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
  static var previews: some View {
    Group{
      MyTextFieldView().previewLayout(.sizeThatFits)
      MyTextFieldView().previewDevice("iPhone Xs")
    }
  }
}
#endif

我们不再需要使用 hack。 Beta 5 带来了一个新的修饰符来设置键盘类型。例如,要使用数字键盘:

.keyboardType(.numberPad)

还有 autocapitalization() 和一个环境值 disableAutocorrection

在 TextField 上设置 .keyboardType(.numberPad)。简单!

要设置 TextField's 键盘类型,您需要添加修饰符 .keyboardType()

TextField(placeHolder, text: "your text here")
    .keyboardType(.numberPad)

这对我有用:

import UIKit
import SwiftUI

class UIKitTextField: UITextField, UITextFieldDelegate {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        delegate = self
    }

    required override init(frame: CGRect) {
        super.init(frame: frame)
        delegate = self
        self.setContentHuggingPriority(.defaultHigh, for: .vertical)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        resignFirstResponder()
        return true
    }

}

struct UBSTextField : UIViewRepresentable {

    @Binding var myText: String
    let placeHolderText: String

    func makeCoordinator() -> UBSTextField.Coordinator {
        return Coordinator(text: $myText)
    }

    class Coordinator: NSObject {
        var textBinding: Binding<String>
        init(text: Binding<String>) {
            self.textBinding = text
        }

        @objc func textFieldEditingChanged(_ sender: UIKitTextField) {
            self.textBinding.wrappedValue = sender.text ?? ""
        }
    }

    func makeUIView(context: Context) -> UIKitTextField {

        let textField = UIKitTextField(frame: .zero)

        textField.addTarget(context.coordinator, action: #selector(Coordinator.textFieldEditingChanged(_:)), for: .editingChanged)

        textField.text = self.myText
        textField.placeholder = self.placeHolderText
        textField.borderStyle = .none
        textField.keyboardType = .asciiCapable
        textField.returnKeyType = .done
        textField.autocapitalizationType = .words
        textField.clearButtonMode = .whileEditing

        return textField
    }

    func updateUIView(_ uiView: UIKitTextField,
                      context: Context) {
        uiView.text = self.myText
    }
}

Xcode 13 - iOS & 观看OS 应用程序

如果您正在制作 WatchOS 应用,同时制作 iOS 应用,您需要为 OS 添加条件检查,如下面的代码

           #if os(iOS)
            TextField(placeHolder, text: $text)
                .keyboardType(.numbersAndPunctuation)
            #endif