How to set Keyboard type of TextField in SwiftUI?

后端 未结 7 1530
灰色年华
灰色年华 2021-02-03 19:46

I can\'t seem to find any information or figure out how to set the keyboard type on a TextField for SwiftUI. It would also be nice to be able to enable the secure text property,

7条回答
  •  感动是毒
    2021-02-03 20:21

    The following wraps a UITextField class called UIKitTextField using UIViewRepresentable. The keyboard type is set to .decimalPad but could be set to any valid keyboard type.

    //  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)
      }
    }
    

    In the ContentView.Swift I created two TextFields. The first is the wrapped UIKit UITextField and the second is the SwiftUI TextField. The data binding is the same so each will display the same text as it is entered.

    // 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) {
          $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
    

提交回复
热议问题