NEW: Join my free 100 Days of SwiftUI challenge today! >>

Presenting an alert

Paul Hudson    @twostraws   

Fully updated for Xcode 11.2

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 two-way binding to that property:

.alert(isPresented: $showingPaymentAlert) {
    // more to come
}

It’s 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.

What alert? Well, that’s the alert that will show a confirmation of the price they paid plus an OK button. Put this in place of the // more to come comment:

Alert(title: Text("Order confirmed"), message: Text("Your total was $\(totalPrice, specifier: "%.2f") – thank you!"), dismissButton: .default(Text("OK")))

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") {
    self.showingPaymentAlert.toggle()
}

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

Further reading

SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.

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: 5.0/5