Dismissing SwiftUI modal views in iOS 15 and macOS 12

Scott Matthewman
4 min readJun 11, 2021

This post discusses changes to SwiftUI first revealed at WWDC 2021 and are still in beta, so are subject to change.

A modal view built using SwiftUI

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:

  1. Pass a binding to the boolean used in the isPresented: clause of the presenting modifier, and manually set it to false.
  2. 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

--

--

Scott Matthewman

Scott is a software developer during the day and a theatre critic & director of an evening. Which is the worst superhero identity ever.