Skip to main content

Presenting an alert

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

Presenting an alert 관련

SwiftUI by Example

Back to Home

Presenting an alert | SwiftUI by Example

Presenting an alert

Updated for Xcode 15

There's one more thing to add in order to finish off this screen, which is to make the Confirm Order button work. We're not actually going to send the order off somewhere, but we are going to show an alert confirming that it all went through successfully.

Like other things in this form this requires us to add another @State property, this time tracking whether the alert is visible or not. And this is where I hope the reactive nature of SwiftUI starts to become clear: we don't say “show the alert” or “hide the alert” like we would do in UIKit, but instead say “here are the conditions where the alert should be shown” and let SwiftUI figure out when those conditions are met.

So, first let's create another @State property saying that the payment alert isn't currently showing:

@State private var showingPaymentAlert = false

Now we'll attach an alert() modifier to our form, with a simple title, a two-way binding to that property, and some text to show as the alert's message:

.alert("Order confirmed", isPresented: $showingPaymentAlert) {
    // add buttons here
} message: {
    Text("Your total was \(totalPrice) – thank you!")
}

That uses a two-way binding so that SwiftUI knows to show the alert when showingPaymentAlert becomes true, and will also set showingPaymentAlert back to false when the alert is dismissed.

Where I've placed the // add buttons here comment is where to add some custom buttons for your alert if you want them, but as we haven't added any SwiftUI will automatically add a default “OK” button that dismisses the alert.

Now we can make that alert show whenever we want, just by setting showingPaymentAlert to true. So, change our button to this:

Button("Confirm order") {
    showingPaymentAlert.toggle()
}

Run the program and see what you think – it's really coming together now!

An iOS alert showing the order was confirmed.
An iOS alert showing the order was confirmed.
Further reading
Article(s) > Working with presentations

Working with presentations
How to show an alert | SwiftUI by Example

How to show an alert
Similar solutions…
How to show an alert | SwiftUI by Example

How to show an alert
How to add actions to alert buttons | SwiftUI by Example

How to add actions to alert buttons
How to add a TextField to an alert | SwiftUI by Example

How to add a TextField to an alert
How to show multiple alerts in a single view | SwiftUI by Example

How to show multiple alerts in a single view
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks

이찬희 (MarkiiimarK)
Never Stop Learning.