I am new to SwiftUI from UIKit and I have a question regarding the behavior of the TextField.
struct ContentView: View {
@State private var text = ""
@State private var words: [String] = []
var body: some View {
Form {
Section {
TextField("Input", text: $text) {
words.insert(text, at: 0)
text = ""
}
}
Section {
Button("Clear") {
text = ""
}
}
Section {
ForEach(words, id: .self) { word in
Text(word)
}
}
}
}
}
The behavior I would like to do is to clear the text and add it to a list. After the input the text field will be cleared. The problem now is that text = ""
is called but it didn’t clean up the field. However, by having a separate button below it works correctly.
For the context, I need to set the minimum deployment version to iOS14
and I am using Xcode 14.0.1
.
I have tried to move it to a function but didn’t help either.
2
Answers
in Clear Button before
text = ""
just append in the arrayFor iOS 14, you can achieve it by using
UIViewRepresentable
of UITextField andCoordinator
class to manage textfield delegate.Here is the working code for the same.
In iOS 15 and above versions, you can manage it by using the
onCommit
method of TextField