< How to customize the submit button for TextField, SecureField, and TextEditor | How to get bordered buttons that stand out > |
Updated for Xcode 14.0 beta 1
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
SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.