Add actions to alert buttons in SwiftUI

In this tutorial, we will see how to add actions to alert buttons in SwiftUI.

We can add actions to alert buttons using the .alert modifier along with the Alert structure in SwiftUI.

Now, follow the steps below to create an alert with buttons that will trigger different actions.

Create a SwiftUI View

First of all, I will create a SwiftUI view. This view will contain a state property, and a button that will trigger the alert.

import SwiftUI

struct ContentView: View {
    // Declare a state variable to control the alert's visibility
    @State private var showAlert = false
    
    var body: some View {
        //Create a button that triggers the alert by toggling the showAlert state
        Button("Show Alert") {
            // When the button is tapped, set showAlert to true
            self.showAlert = true
        }
        .padding()
        // Add alert modifier here
    }
}

In the above program, I have declared a boolean @State variable that is showAlert and initialized it with false.  When this state variable is toggled to true, it will display an alert in our SwiftUI view.

Then, I have created a button, so when we tap this button it will set the state variable (showAlert) to true and show the alert.

Add the Alert Modifier

We can display an alert using the .alert modifier when a certain condition is met (in this case, showAlert being true).

.alert(isPresented: $showAlert) {
    // Create an Alert structure here
}

In the above code, the .alert modifier uses a boolean binding (isPresented) to control the visibility of the alert. When the bound boolean (showAlert ) transitions to true, the alert will be displayed, and when it becomes false, the alert will be dismissed.

Create an Alert structure

Now, Inside the .alert, We have to create an Alert structure with a title, message, and buttons.

Alert(
    title: Text("Alert Title"),
    message: Text("Alert Message"),
    primaryButton: .default(Text("Ok")) {
        // Action for the Ok button
    },
    secondaryButton: .destructive(Text("Cancel")) {
        // Action for the Cancel button
    }
)

The above code will create an alert with a title (“Alert Title“) and a message (“Alert Message“). It includes two buttons, the “Ok” button is set as the default action, and the “Cancel” button is styled as a destructive action.

Define Actions for Buttons

Now, within each button (primaryButton and secondaryButton), we have to define the actions we want to perform when each button is tapped.

primaryButton: .default(Text("Ok")) {
    //Action goes here
    print("OK button tapped")
},
secondaryButton: .destructive(Text("Cancel")) {
    //Action goes here
    print("Cancel button tapped")
}

When we tap Ok button it will print “OK button tapped” into the console, similarly when we press the Cancel button it will print “Cancel button tapped” into the console.

Here is the complete code below.

import SwiftUI

struct ContentView: View {
    @State private var showAlert = false
    
    var body: some View {
        Button("Show Alert") {
            self.showAlert = true
        }
        .alert(isPresented: $showAlert) {
            Alert(
                title: Text("Alert Title"),
                message: Text("Alert Message"),
                primaryButton: .default(Text("Ok")) {
                    print("OK button tapped")
                },
                secondaryButton: .destructive(Text("Cancel")) {
                    print("Cancel button tapped")
                }
            )
        }
    }
}

Output:

Add actions to alert buttons in SwiftUI

Leave a Reply

Your email address will not be published. Required fields are marked *