BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

How to take action when the user submits a TextField

Paul Hudson    @twostraws   

Updated for Xcode 14.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

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

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

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.