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.