|

How to Use iOS SwiftUI TextField onSubmit Modifier

SwiftUI introduced the onSubmit modifier in iOS 15, providing a clean and straightforward way to handle text input submission. This article will detail the usage of onSubmit with the TextField in SwiftUI, including a comprehensive example.

Basic Usage of onSubmit

Below is an example that demonstrates the simplest usage of the onSubmit modifier:

struct ContentView: View {
    @State private var text = ""

    var body: some View {
        TextField("Enter text", text: $text)
            .onSubmit {
                print("Text was submitted: \(text)")
            }
    }
}
  • @State Property Wrapper: This keeps track of the text input in the TextField.
  • TextField: This sets up the TextField with a placeholder and binds it to the text state variable.
  • onSubmit: This is where the action to be performed upon text submission is defined. In this example, it prints the submitted text to the console.

Advanced Usage of onSubmit

Input Validation

You can perform validation of the input text using onSubmit. Here’s an example:

struct ContentView: View {
    @State private var email = ""
    @State private var isValid = true

    var body: some View {
        VStack {
            TextField("Enter email", text: $email)
                .onSubmit(validateEmail)
                .border(isValid ? Color.clear : Color.red)
        }
    }

    private func validateEmail() {
        isValid = email.contains("@") && email.contains(".")
    }
}

The onSubmit modifier in SwiftUI provides a clear and efficient way to handle text submissions in an application. From basic text logging to complex scenarios like validation and navigation, it equips developers with the tools needed to create interactive and user-friendly interfaces.

Similar Posts

Leave a Reply