WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to show multiple alerts in a single view

Paul Hudson    @twostraws   

Updated for Xcode 14.2

SwiftUI makes it relatively easy to show a single alert, but things become trickier if you try to show two or more alerts from a single view – you might find that one alert works and the other doesn’t, for example.

To solve this, you need to make sure you attach no more than one alert() modifier to each view. That might sound limiting, but remember: you don’t need to attach the alerts to the same view – you can attach them anywhere. In fact, you might find that attaching them directly to the thing that shows them (e.g. a button) works best for you.

As an example, we can write some code to define two @State properties that each control an alert being shown. Rather than attaching both alert() modifiers to the same VStack, this attaches them each to whichever button is responsible for showing that alert:

struct ContentView: View {
    @State private var showingAlert1 = false
    @State private var showingAlert2 = false

    var body: some View {
        VStack {
            Button("Show 1") {
                showingAlert1 = true
            }
            .alert(isPresented: $showingAlert1) {
                Alert(title: Text("One"), message: nil, dismissButton: .cancel())
            }

            Button("Show 2") {
                showingAlert2 = true
            }
            .alert(isPresented: $showingAlert2) {
                Alert(title: Text("Two"), message: nil, dismissButton: .cancel())
            }
        }
    }
}

Download this as an Xcode project

If you try moving both alert() modifiers to the VStack, you’ll find that only one works, which is why the above approach is so useful.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.