Ive got a done button on a numberpad and when i enter a value and press done the value isnt saved/registered. My code is below:
Im using UIRepresentable protocol (courtesy of Rajeev Kumar S)
struct TestTextfield: UIViewRepresentable {
@Binding var text: String
var keyType: UIKeyboardType
func makeUIView(context: Context) -> UITextField {
let textfield = UITextField()
textfield.keyboardType = keyType
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44))
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(textfield.doneButtonTapped(button:)))
toolBar.items = [doneButton]
toolBar.setItems([doneButton], animated: true)
textfield.inputAccessoryView = toolBar
return textfield
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
}
extension UITextField{
@objc func doneButtonTapped(button:UIBarButtonItem) -> Void {
self.resignFirstResponder()
}
}
And ive got this in my content view
struct ContentView : View {
@State var text = ""
var body: some View {
TestTextfield(text: $text, keyType: UIKeyboardType.phonePad)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 50)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(Color.blue, lineWidth: 4)
)
}
This is what i am using:
Xcode 11.5
You just need to update your representable class to this!
struct TestTextfield: UIViewRepresentable {
@Binding var text: String
var keyType: UIKeyboardType
func makeUIView(context: Context) -> UITextField {
let textfield = UITextField()
textfield.keyboardType = keyType
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44))
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(textfield.doneButtonTapped(button:)))
toolBar.items = [doneButton]
toolBar.setItems([doneButton], animated: true)
textfield.inputAccessoryView = toolBar
textfield.delegate = context.coordinator
return textfield
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
func makeCoordinator() -> Coordinator {
Coordinator($text)
}
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
init(_ text: Binding<String>) {
self._text = text
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
text = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? ""
return true
}
}
}
Try it!