I'm looking to clear my FirstResponder TextField with an independent button that will save the field data and clear the input content so that we can write again. My code is based on the work of :
Matteo Pacini -> https://stackoverflow.com/a/56508132/15763454
The Clear variable should when it goes to True clear the field, it works when I click the button but I have to additionally enter a character in the text field for it to clear. This is logical since the "textFieldDidChangeSelection" function only runs when the textfield is changed
How can I make sure that as soon as my Clear variable changes to True the textfield is automatically deleted?
struct ContentView : View {
@State var text: String = ""
@State var Clear = false
var body: some View {
HStack{
Spacer()
Button(action: set,label: {
Text("Clic")
})
Spacer()
CustomTextField(text: $text,clear: $Clear,isFirstResponder: true)
.frame(width: 300, height: 50)
.background(Color.red)
}
}
func set(){
self.Clear=true
}
}
struct CustomTextField: UIViewRepresentable {
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
@Binding var clear: Bool
var didBecomeFirstResponder = false
init(text: Binding<String>,clear: Binding<Bool>) {
_text = text
_clear = clear
}
func textFieldDidChangeSelection(_ textField: UITextField) {
text = textField.text ?? ""
if clear == true{
textField.text?.removeAll()
clear = false
}
}
}
@Binding var text: String
@Binding var clear: Bool
var isFirstResponder = false
func makeUIView(context: UIViewRepresentableContext<CustomTextField>) -> UITextField {
let textField = UITextField(frame: .zero)
textField.delegate = context.coordinator
return textField
}
func makeCoordinator() -> CustomTextField.Coordinator {
return Coordinator(text: $text,clear: $clear)
}
func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<CustomTextField>) {
uiView.text = text
if isFirstResponder && !context.coordinator.didBecomeFirstResponder {
uiView.becomeFirstResponder()
context.coordinator.didBecomeFirstResponder = true
}
}
}
Just replace
func set() {
self.Clear=true
}
with
func set() {
self.text = ""
}
This immediately clears the text.