avatar
Published on

Adding a TextField to an Alert in SwiftUI

Authors
  • avatar
    Name
    Mick MacCallum
    Twitter
    @0x7fs

In iOS 16, SwiftUI added the ability to collect user input in an alert. This is a great way to prompt the user for input without having to navigate to a new screen. You can add multiple TextFields, SecureFields, or both in combination with buttons.

For example, we can add a TextField to an alert used to let the user name a file while saving it:

struct ContentView: View {
    @State private var fileName = ""
    @State private var isAlertPresented = false

    var body: some View {
        Button("Save file") {
            isAlertPresented = true
        }
        .alert("Enter a file name", isPresented: $isAlertPresented) {
            TextField("Input a file name", text: $fileName)

            Button("Save") {
                print("Saving file named: \(fileName)")
            }
        } message: {
            Text("What would you like to name your new file?")
        }
    }
}

Since we can add multiple TextFields and SecureFields, we can also add both to the same alert to create a simple login form:

struct ContentView: View {
    @State private var username = ""
    @State private var password = ""
    @State private var isAlertPresented = false

    var body: some View {
        Button("Login") {
            isAlertPresented = true
        }
        .alert("Login", isPresented: $isAlertPresented) {
            TextField("Enter your username", text: $username)
            SecureField("Enter your password", text: $password)

            Button("Login") {
                // Login
            }
        } message: {
            Text("Enter your username and password to login")
        }
    }
}