Search code examples
iosswiftswiftuiios13

How to present an Alert with SwiftUI


In SwiftUI I discovered the Alert type. But I wonder how to show it with the presentation method.

Initializing an Alert is pretty easy. But how to use the binding?

struct ContentView : View {
    var body: some View {
        Button(action: {
            // Don't know how to use the `binding` below
            presentation(binding, alert: {
                Alert(title: Text("Hello"))
            })
        }, label: {
            Text("asdf")
        })
    }
}

The binding is of type Binding<Bool>


Solution

  • 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"))
            })
        }
    }