- My code: I use
onCommitclosure to be able to perform an action by pressing the Enter key when theTextFieldis being focused.
import SwiftUI
struct ContentView: View {
@State private var text = ""
var body: some View {
TabView {
TextField(
"",
text: $text,
onCommit: { print("onCommit") } // I have a problem here
)
.tabItem {
Text("Tab 1")
}
Text("Tab 2")
.tabItem {
Text("Tab 2")
}
Text("Tab 3")
.tabItem {
Text("Tab 3")
}
}
}
}
- My problem: The
onCommitclosure is also always triggered when I switch to another tab, making my App perform an unexpected action. - My questions:
- This is the bug or the feature?
- Is there any other way to perform an action by pressing Enter key?
- I have found the solution by following the deprecated message.
Deprecated
Use
init(_:text:prompt:)instead. Add theonSubmit(of:_:)view modifier for theonCommitbehavior, andonFocus(_:)for theonEditingChangedbehavior.
import SwiftUI
struct ContentView: View {
@State private var text = ""
var body: some View {
TabView {
TextField("", text: $text)
.onSubmit { // new api
print("onCommit")
}
.tabItem {
Text("Tab 1")
}
Text("Tab 2")
.tabItem {
Text("Tab 2")
}
Text("Tab 3")
.tabItem {
Text("Tab 3")
}
}
}
}
-
onSubmitdoesn't trigger every time I switch to another tab.