Updated for Xcode 14.2
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 project
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 project
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.