How to present an Alert with swiftUI
You can use a @State
variable as the binding. Alternatively you can use a @EnvironmentObject
variable that uses a BindableObject
.
I think you need to call presentation
on the root View to get it to work, adding it to a Stack
, Group
, etc. doesn't seem to work.
This snippet seems to do the trick. Note that @State
variable is set to false after the alert is dismissed.
struct ContentView: View {
@State var showsAlert = false
var body: some View {
Button(action: {
self.showsAlert = true
}, label: {
Text("asdf")
}).presentation($showsAlert, alert: {
Alert(title: Text("Hello"))
})
}
}
.presentation()
was actually deprecated in Beta 4. Here is a version that currently works with the .alert()
Modifier.
struct ContentView: View {
@State var showsAlert = false
var body: some View {
Button(action: {
self.showsAlert.toggle()
}) {
Text("Show Alert")
}
.alert(isPresented: self.$showsAlert) {
Alert(title: Text("Hello"))
}
}
}