How to set Keyboard type of TextField in SwiftUI?

后端 未结 7 1414
灰色年华
灰色年华 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:33

    This works for me:

    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
            init(text: Binding) {
                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
        }
    }
    

提交回复
热议问题