I have a button that is supposed to add text from a TextField into a list, either when the button is pressed, or "return" is pressed on the on-screen keyboard, and then clear the TextField. When I press the button this all works flawlessly, however when I press "return" the item gets added onto the list but the TextField is never cleared. I do not understand why it does not get cleared, the same code is called when "return" is pressed as when the button is pressed.
TextField("Add Item", text: $newItem, onCommit: {
self.items.append(self.newItem)
ShoppingListData.saveItems(self.items)
self.newItem = ""
})
.padding(.horizontal, 10)
.padding(.vertical, 6)
.background(Color(.systemGray6))
.cornerRadius(10)
Button(action: {
self.items.append(self.newItem)
ShoppingListData.saveItems(self.items)
self.newItem = ""
}) {
Image(systemName: "plus")
}
As you can see both the button and the onCommit use the same code
self.items.append(self.newItem)
ShoppingListData.saveItems(self.items)
self.newItem = ""
However for some reason the self.newItem = ""
only works when the button is pressed and not when "return" is pressed and onCommit is called.
I’ve looked up online how to clear text fields and as far as I am aware self.newItem = ""
should be clearing the text field but it does not.
2
Answers
You can add UIApplication.shared.endEditing() code in your Button:
and add this extension:
I hope this will help you.
—- In SwiftUI —-
We can use textField modifier ‘onCommit’, its action is set to clear the text by setting self.text to an empty string.
—- In UIKit —-
You need implement the textFieldShouldReturn method, which is called when the "return" key is pressed on the on-screen keyboard. In this method, we clear the text field by setting its text property to an empty string.