NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

How to show an alert

Paul Hudson    @twostraws   

Updated for Xcode 12.5

SwiftUI provides two ways of showing alerts, depending on whether you want to present the alert when a Boolean becomes true or when an optional value is set.

The code to create a basic SwiftUI alert looks like this:

Alert(title: Text("Important message"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))

That defines a title and message, like you’d see in a UIAlertController, then adds a dismiss button with a default style and the text “Got it!”.

To show that alert the first approach is to define some sort of bindable condition that determines whether the alert should be visible or not. You then attach that to your main view, which presents the alert as soon as its condition becomes true.

For example, this code creates a showingAlert Boolean that tracks whether the sunscreen message should be shown or not, sets that Boolean to true when a button is tapped, then creates and attaches an alert view using that Boolean so it appears when the button is tapped:

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

    var body: some View {
        Button("Show Alert") {
            showingAlert = true
        }
        .alert(isPresented: $showingAlert) {
            Alert(title: Text("Important message"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))
        }
    }
}

Tip: Presenting an alert like this will automatically set showingAlert back to false when the dismiss button is tapped.

The second approach to creating alerts is to bind to some optional state that conforms to Identifiable, which will cause the alert to be shown whenever the object’s value changes.

There are two advantages to this method:

  1. You can attach any object you like at runtime, so your alert can show any number of different pieces of data.
  2. SwiftUI automatically unwraps the optional when it has value, so you can be sure it exists by the time you want to show your alert – no need to check and unwrap the value yourself.

For example, this shows one alert with two different values depending on which TV show was chosen:

struct TVShow: Identifiable {
    var id: String { name }
    let name: String
}

struct ContentView: View {
    @State private var selectedShow: TVShow?

    var body: some View {
        VStack(spacing: 20) {
            Text("What is your favorite TV show?")
                .font(.headline)

            Button("Select Ted Lasso") {
                selectedShow = TVShow(name: "Ted Lasso")
            }

            Button("Select Bridgerton") {
                selectedShow = TVShow(name: "Bridgerton")
            }
        }
        .alert(item: $selectedShow) { show in
            Alert(title: Text(show.name), message: Text("Great choice!"), dismissButton: .cancel())
        }
    }
}
Hacking with Swift is sponsored by Stream

SPONSORED Check out Stream's cross-platform open source chat SDK on GitHub! Write once and deploy your app with fully featured chat UI on iOS and macOS.

Go to GitHub

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.5/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.