NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to take action when the user submits a TextField

Paul Hudson    @twostraws   

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

Hacking with Swift is sponsored by Essential Developer

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!

Click to save your free spot now

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.