How to add a TextField to Alert in SwiftUI
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.
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.
You can easily support sarunw.com by checking out this sponsor.
AI Grammar: Correct grammar, spell check, check punctuation, and parphrase.
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.")
})
}
}
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 ShareLittle big improvements in Xcode 14
Small improvements that make a big difference in day-to-day coding.
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.