Member-only story
Dismissing SwiftUI modal views in iOS 15 and macOS 12
This post discusses changes to SwiftUI first revealed at WWDC 2021 and are still in beta, so are subject to change.
If you’ve spent any time working with modal views in SwiftUI, you’ll usually want to have some way of dismissing them in code. As I discussed in my last post, there are a couple of ways to do this:
- Pass a binding to the boolean used in the
isPresented:
clause of the presenting modifier, and manually set it tofalse
. - Access the presentation mode environment object, and call
dismiss()
on its wrapped value.
The second option is the most commonly used form, and looks something like:
struct MyModal: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
// ...
.toolbar {
Button("Close") {
presentationMode.wrappedValue.dismiss()
}
}
}
}
But that’s a bit of a faff, isn’t it? And why do we have to worry about wrappedValue
? That’s part of SwiftUI’s implementation that we shouldn’t have to worry about.
And now, with the latest version of SwiftUI coming for iOS 15, iPadOS 15 and macOS 12 Monterey, there’s a simpler syntax:
struct MyModal_iOS15: View {
@Environment(\.dismiss) var dismiss
var body: some…