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 showAlert = false
    // 2.
    var alert: Alert {
        Alert(title: Text("iOScreator"), message: Text("Hello SwiftUI"), dismissButton: .default(Text("Dismiss")))
    var body: some View {
        // 3.
        Button(action: {
        }) {
            Text("Show Alert")
        // 4.
        .alert(isPresented: $showAlert, content: { self.alert })
  1. The state property is created to determine when the alert will be displayed

  2. an Alert property is declared containing the elements of the Alert.

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

  4. The alert modifier 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.