Updated for Xcode 14.2
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 modifiers, which attach 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.
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.
Link copied to your pasteboard.