< How to read text from a TextField | How to customize the submit button for TextField, SecureField, and TextEditor > |
Updated for Xcode 14.2
New in iOS 15
SwiftUI has an onSubmit()
modifier that can be attached to any view in your hierarchy, and will run a function of your choice when the user has finished entering text into a TextField
or SecureField
.
For example, we could ask the user to enter their password, then run some code when they press return:
struct ContentView: View {
@State private var password = ""
var body: some View {
SecureField("Password", text: $password)
.onSubmit {
print("Authenticating…")
}
}
}
Download this as an Xcode project
For simple examples like that, both TextField
and SecureField
accept a dedicated onCommit
parameter where we can attach our function directly to them. However, the advantage to using onSubmit()
is that it captures all text values submitted in its context, which makes completing forms easier:
struct ContentView: View {
@State private var username = ""
@State private var password = ""
var body: some View {
Form {
TextField("Username", text: $username)
SecureField("Password", text: $password)
}
.onSubmit {
guard username.isEmpty == false && password.isEmpty == false else { return }
print("Authenticating…")
}
}
}
Download this as an Xcode project
SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.