How to present an Alert with swiftUI

Lukas Würzburger picture Lukas Würzburger · Jun 4, 2019 · Viewed 17.1k times · Source

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>

Answer

thisIsTheFoxe picture thisIsTheFoxe · Aug 2, 2019

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