FREE TRIAL: Accelerate your app development career with Hacking with Swift+! >>

How to take action when the user submits a TextField

Paul Hudson    @twostraws   

Updated for Xcode 13.0

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

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Get started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.