Skip to main content

How to add a TextField to an alert

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to add a TextField to an alert 관련

SwiftUI by Example

Back to Home

How to add a TextField to an alert | SwiftUI by Example

How to add a TextField to an alert

Updated for Xcode 15

New in iOS 16

SwiftUI’s alerts can have one or more TextField or SecureField fields alongside their buttons, allowing you to prompt the user for input directly.

For example, we could add a TextField to let the user enter their name into an alert:

struct ContentView: View {
    @State private var showingAlert = false
    @State private var name = ""

    var body: some View {
        Button("Enter name") {
            showingAlert.toggle()
        }
        .alert("Enter your name", isPresented: $showingAlert) {
            TextField("Enter your name", text: $name)
            Button("OK", action: submit)
        } message: {
            Text("Xcode will print whatever you type.")
        }
    }

    func submit() {
        print("You entered \(name)")
    }
}

Download this as an Xcode projectopen in new window

You can add as many fields as you want, mixing TextField and SecureText depending on your goal. For example, this shows a login prompt asking the user to enter their username and password into an alert:

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

    var body: some View {
        Button("Log in") {
            isAuthenticating.toggle()
        }
        .alert("Log in", isPresented: $isAuthenticating) {
            TextField("Username", text: $username)
                .textInputAutocapitalization(.never)
            SecureField("Password", text: $password)
            Button("OK", action: authenticate)
            Button("Cancel", role: .cancel) { }
        } message: {
            Text("Please enter your username and password.")
        }
    }

    func authenticate() {
        if username == "twostraws" && password == "sekrit" {
            print("You're in!")
        } else {
            print("Who are you?")
        }
    }
}

Download this as an Xcode projectopen in new window

Similar solutions…
Presenting an alert | SwiftUI by Example

Presenting an alert
How to add actions to alert buttons | SwiftUI by Example

How to add actions to alert buttons
How to show an alert | SwiftUI by Example

How to show an alert
How to add a border to a TextField | SwiftUI by Example

How to add a border to a TextField
How to add a placeholder to a TextField | SwiftUI by Example

How to add a placeholder to a TextField

이찬희 (MarkiiimarK)
Never Stop Learning.