NEW: Get your ticket for Hacking with Swift Live 2019! >>

< How to group views together   How to show an alert >

Working with presentations

SwiftUI’s declarative approach to programming means that we don’t create and present alert and action sheets in the same way as we did in UIKit. Instead, we define the conditions in which they should be shown, tell it what they should look like, then leave it to figure the rest out for itself.

This is all accomplished using a presentation() modifier, which attaches new UI to our view that will be shown when a condition is satisfied. You can attach as many as you want, and they effectively lie in wait watching until their condition becomes true, at which point they show their UI. For example, you might toggle a Boolean inside a button press, which triggers an alert to show.

You can attach presentations to your main view or any of its children – even to the button that adjusts your state so the presentation triggers. It’s a subtle distinction, but it’s important to understand that these presentations aren’t attached to the button because it’s a button – i.e., that doesn’t in any way make the alert be shown because the button was tapped. Instead, we’re attaching it to our view hierarchy so that SwiftUI is aware that it might be shown at any point.

HACKING WITH SWIFT LIVE This July is a new two-day event where you'll be inspired by great speakers on day one then learn all the amazing new features from WWDC on day two – click here for more information and tickets.

< How to group views together   How to show an alert >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 3.5/5

Click here to visit the Hacking with Swift store >>