I have a form with a TextField that takes in string values to save to an array. I use the onCommit to store the entered value into the array and to then clear the TextField value. Debug statements show that the value, called newTag, is indeed cleared, however this is not reflected in the view. Can anyone help me understand this behavior and how to get the functionality I’m looking for?
struct ContentView: View {
@State private var tags = [String]()
@State private var newTag = ""
var body: some View {
NavigationView {
Form {
Section(header: Text("New Tag")) {
TextField("Enter a new tag", text: $newTag, onCommit: {
self.addNewTag()
})
}
Section(header: Text("Tags")) {
ForEach(tags, id: \.self) { tag in
Text(tag)
}
}
}
}
}
private func addNewTag() {
guard !newTag.isEmpty else { return }
tags.append(newTag)
newTag = ""
}
}