How to add a TextField to Alert in SwiftUI

⋅ 2 min read ⋅ SwiftUI Alert WWDC22

Table of Contents

In iOS 15 and prior, having TextField in an alert isn't supported with an alert modifier. In iOS 16, we can do this by just adding a TextField as an alert action.

Text field in an alert.
Text field in an alert.

Alert in iOS 15

alert modifier in SwiftUI accept a ViewBuilder for both message and its actions.

But if you try to use anything other than Text for the message and Button for the actions, SwiftUI will simply ignore that views.

struct ContentView: View {
@State private var presentAlert = false
var body: some View {
Button("Show Alert") {
presentAlert = true
}
.alert("Title", isPresented: $presentAlert, actions: {
// Any view other than Button would be ignored
TextField("TextField", text: .constant("Value"))
}, message: {
// Any view other than Text would be ignored
TextField("TextField", text: .constant("Value"))
})
}
}

TextField gets ignored when used as action and message content in iOS 15.

TextField is ignored in the old alert API.
TextField is ignored in the old alert API.

How to add a TextField to Alert in SwiftUI

In iOS 16, actions view builder allow two new view, TextField and SecureField.

We can have a text field in an alert by using TextField or SecureField as action content.

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

var body: some View {
Button("Show Alert") {
presentAlert = true
}
.alert("Login", isPresented: $presentAlert, actions: {
TextField("Username", text: $username)
SecureField("Password", text: $password)

Button("Login", action: {})
Button("Cancel", role: .cancel, action: {})
}, message: {
Text("Please enter your username and password.")
})
}
}
TextField and SecureField are supported in iOS 16.
TextField and SecureField are supported in iOS 16.

Read more article about SwiftUI, Alert, WWDC22, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
Little big improvements in Xcode 14

Small improvements that make a big difference in day-to-day coding.

Next
How to initialize variables in constructor body in Dart

Initialize instance variable is not as straightforward as you think. Let's learn how to do it.

← Home