Showing an Alert with SwiftUI

Alerts.png

Showing an alert is a great way to notify a user of important information related to your app such as a payment going through or an error loading something from the server. In SwiftUI Apple has added a modifier that makes it super easy to show an alert based off your view’s state.

Setting Up

For this example we’ll control showing an alert by tapping on a button. So first thing we’ll need to do is create a button and a state property to keep track of if the alert is showing.

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {

        Button(action: {
            self.showingAlert.toggle()
        }) {
          Text("Show Alert")
        }
    }
}

Adding the Alert

OK great, now that we have a button it’s time to add an alert. To do that we’ll add the .alert modifier to our button, using a binding to showingAlert to control if it is presented. Then in the content closure we’ll create the alert itself.

.alert(isPresented: $showingAlert) {
  Alert(title: Text("Alert!"), message: Text("You showed an alert"))
}

That’s all there is to it! Now when you tap on the button you’ll see an alert pop up. What’s even better is since we’re using a binding to our showingAlert property when the alert is dismissed that property is automatically switched back to false for us.

Check out some other recent tutorials

Previous
Previous

Using Transitions in SwiftUI

Next
Next

Horizontal Scrolling in SwiftUI