@brendan asks if there's a typo in the article?
it could be directly on the button, but it can be anywhere else in the view...
Please note the article was transcribed from the video. If you rewatch the video he's flying through an example and probably misspoke. I agree with you, he probably meant to say you can add the .onSubmit()
to the TextField
. But don't sleep on the advice that the .onSubmit()
can also be attached to other structures in the view hierarchy.
Experimentation will show that you can attach onSubmit()
to some structures, but not all of them. Also, it's important to know that when you attach .onSubmit()
to several structures, SwiftUI will fire the ones higher in the structure tree first.
Here's some modifications to the lesson's code. I urge you to paste this into your project and experiment. There are several places in the code below where I've added .onSubmit
to the view's structures. Comment and uncomment each one, then run the application. The addNewWord()
function will print a comment showing where it was called.
struct WordListView: View {
@State private var newWord = "mule"
let rootWord = "cromulent"
@State private var usedWords: [String] = []
var body: some View {
NavigationStack {
List {
Section{
TextField("Guess", text: $newWord)
.onSubmit { addNewWord(from: "TextField") } // ๐๐ผ comment out to experiment
}
.onSubmit { addNewWord(from: "Section 1") } // ๐๐ผ comment out to experiment
Section { ForEach(usedWords, id: \.self) { Text($0) } }
// .onSubmit { addNewWord(from: "Section 2") } // ๐๐ผ does not work
Section {
Text("Rule #1: Keep Coding")
Text("Rule #2: Have Fun")
Button("Add Word") { } // do nothing
// .onSubmit { addNewWord(from: "Button") } // ๐๐ผ does not work
}
}
.navigationTitle(rootWord)
// .onSubmit { addNewWord(from: "List") } // ๐๐ผ comment out to experiment
}
}
// ๐๐ผ add for debugging
func addNewWord(from: String) {
let answer = newWord.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
guard answer.count > 0 else { return }
usedWords.insert(answer, at: 0)
newWord = ""
print("from \(from)") // ๐๐ผ for debugging!
}
}
Keep Coding
This is a great lesson in experimentation!