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,
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
}
}