iPhones showing alerts

How to Show Alerts Using SwiftUI: A Quick Guide

SwiftUI, Apple’s modern declarative framework for building user interfaces across its platforms, provides a straightforward and intuitive way to display alerts to users. Alerts are essential for presenting important information or requesting confirmation from users. In this article, we’ll explore how to show alerts using SwiftUI, enabling you to enhance the user experience of your iOS, macOS, or watchOS apps.

Find the source code here if you want to dive in 🤿

Step 1: Defining an Alert

To display an alert, you need to define an instance of the Alert structure. The Alert structure consists of a title, message, and a set of buttons representing the options available to the user.

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

    var body: some View {
        VStack {
            // Your app's content here

            Button("Show Alert") {
                showAlert = true
            }
        }
        .alert(isPresented: $showAlert) {
            Alert(
                title: Text("Alert Title"),
                message: Text("Alert message goes here"),
                dismissButton: .default(Text("OK"))
            )
        }
    }
}

In the above example, we create a ContentView view with a button labelled “Show Alert.” When the button is tapped, we set the showAlert state variable to true, triggering the presentation of the alert. The .alert modifier is used to bind the presentation of the alert to the value of the showAlert state variable.

Step 2: Customize the Alert

You can customize the appearance and behaviour of the alert by adding more buttons, changing button styles, or attaching actions to buttons. Let’s see an example:

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

    var body: some View {
        VStack {
            // Your app's content here

            Button("Show Alert") {
                showAlert = true
            }
        }
        .alert(isPresented: $showAlert) {
            Alert(
                title: Text("Delete Item"),
                message: Text("Are you sure you want to delete this item?"),
                primaryButton: .destructive(Text("Delete")) {
                    // Action to perform on delete
                },
                secondaryButton: .cancel()
            )
        }
    }
}

In this example, we added a secondary button labelled “Cancel” using the .cancel() modifier. Additionally, a primary button labelled “Delete” is configured with the .destructive() modifier, indicating its potentially destructive nature. You can attach closures to these buttons to perform actions based on user interaction.

Step 3: Presenting Alerts Conditionally

You might want to present an alert conditionally based on certain criteria. For instance, you may want to show an error message only when an error occurs. You can achieve this by modifying the isPresented binding of the .alert modifier.

struct ContentView: View {
    @State private var showAlert = false
    @State private var showError = false

    var body: some View {
        VStack {
            // Your app's content here

            Button("Show Error") {
                showError = true
            }
        }
        .alert(isPresented: $showAlert) {
            Alert(
                title: Text("Error"),
                message: Text("An error occurred."),
                dismissButton: .default(Text("OK"))
            )
        }
        .onAppear {
            if showError {
                showAlert = true
            }
        }
    }
}

In this example, we introduce a new state variable called showError. When the “Show Error” button is tapped, we set showError to<em> true</em>, which triggers the alert to be presented when the view appears.

Conclusion

With SwiftUI, displaying alerts to users is a breeze. By defining an instance of the Alert structure and using the .alert modifier, you can create and present alerts with customized buttons and actions. By following the steps outlined in this guide, you can enhance the user experience of your SwiftUI apps by effectively communicating important information and interacting with your users.

Remember to check out my other SwiftUI articles:

Building SwiftUI Apps With Firestore Integration

Transparent List in SwiftUI

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments