How to present an Alert with swiftUI
.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")) } }}
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")) }) }}
Full Code of Alert with dismiss and okay action:
Code:
import SwiftUIstruct ContentView: View { @State private var isAlert = false var body: some View { Button(action: { self.isAlert = true }) { Text("Click Alert") .foregroundColor(Color.white) } .padding() .background(Color.blue) .alert(isPresented: $isAlert) { () -> Alert in Alert(title: Text("iOSDevCenters"), message: Text("This Tutorial for SwiftUI Alert."), primaryButton: .default(Text("Okay"), action: { print("Okay Click") }), secondaryButton: .default(Text("Dismiss"))) } }}struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() }}
Output: