Skip to main content

How to take action when the user submits a TextField

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to take action when the user submits a TextField 관련

SwiftUI by Example

Back to Home

How to take action when the user submits a TextField | SwiftUI by Example

How to take action when the user submits a TextField

Updated for Xcode 15

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 projectopen in new window

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 projectopen in new window

Similar solutions…
How to make a TextField expand vertically as the user types | SwiftUI by Example

How to make a TextField expand vertically as the user types
How to make buttons that repeat their action when pressed | SwiftUI by Example

How to make buttons that repeat their action when pressed
How to show an action sheet | SwiftUI by Example

How to show an action sheet
How to add custom swipe action buttons to a List row | SwiftUI by Example

How to add custom swipe action buttons to a List row
How to dismiss the keyboard for a TextField | SwiftUI by Example

How to dismiss the keyboard for a TextField

이찬희 (MarkiiimarK)
Never Stop Learning.