SwiftUI Alert Tutorial

An Alert displays an alert message to the user. The alert will be displayed using the presentation method which can added to a view. In this tutorial we will display an alert when the user clicks a button. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIAlertTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView : View {
    // 1.
    @State private var isShowingAlert = false
      
    var body: some View {
        // 2.
        Button(action: {
            self.isShowingAlert = true
        }) {
            Text("Show Alert")
        }
        // 3.
        .presentation($isShowingAlert) {
            Alert(title: Text("iOScreator"), message: Text("Hello SwiftUI"), dismissButton: .default(Text("Dismiss")))
        }
    }
}
  1. The state property is created to determine when the alert will be displayed

  2. A button is created, which will set the state property to true when clicked.

  3. The presentation method is called which will display the Alert.

In the preview pane enable the Live view and select the Show Alert button. The Alert will be displayed.

The source code of the SwiftUIAlertTutorial can be downloaded at the ioscreator repository on Github.