Adam Rush

@Adam9Rush

22 March, 2022

Introduction

You’re building your SwiftUI application, and you’re wondering how to present an alert view to your users? Well, it’s dead easy with SwiftUI by using the Alert() API that we have available.

Displaying an alert to your customers is often necessary, especially if they’re confirming an action, such as removing an item from a list or similar. In your UIKit days, you’d be using a UIAlertController.

Presenting an Alert in SwiftUI

Don’t be fooled to start using the Alert API, because this is now deprecated and so you should start using the .alert() this is easy to be mistaken.

struct TransactionsView: View {
    @State private var isShowingAlert = false
    var body: some View {
        Button("View Transactions") {
            isShowingAlert = true
        }
        .alert("Welcome, Adam!", isPresented: $isShowingAlert) {}
    }
}

You’re building on the blocks of the brand new SwiftlyRush Bank ;]! In the above example, you’re displaying a new button that will show our transactions, but first, they must log in to the application.

Tapping this button will display the “Welcome, Adam!” alert.

It’s that simple, and you can go ahead and define various parameters:

.alert("Welcome, Adam!", isPresented: $isShowingAlert) {
      // Login to the bank
    } message: {
      Text("You're now logged in!")
}

You can now specify a separate message that will be formatted below the title.

What is incredible is that you can go one step further and pass in a generic object so that your alert can use this data.

.alert("Welcome, \(user.fullName)", isPresented: $showingAlert, presenting: user) { user in
      // Do some action
    } message: { user in
      Text("You're logged in and your balance is \(user.balance)")
}

In your above example, you’re passing in a User object which is a basic struct that we have created before and injecting it into our alert so that we can now display the user’s full name and balance.

An alert displaying the user's full name and balance.

What Next?

I am curious to see what you can do next; how about adding multiple action buttons? You could even attempt to display something other than a Text object; is that even possible?

Let me know and get in touch with your examples :]

You can learn more about SwiftUI basics here.

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.