BLACK FRIDAY: Save 50% on all books and bundles! >>

How to make a view dismiss itself

Paul Hudson    @twostraws   

Updated for Xcode 12.0

When you show a SwiftUI view using a sheet, it’s common to want to dismiss that view when something happens – when the user taps on a button, for example. There are two ways of solving this in Swift, and I’m going to show you both so you can decide which suits your needs.

The first option is to tell the view to dismiss itself by modifying its presentation state. To do this, first add a new environment property to the view you want to dismiss:

@Environment(\.presentationMode) var presentationMode

Then, when you’re ready, use this line of code to have the view dismiss itself:


The other option is to pass a binding into the view that was shown, so it can changing the binding’s value back to false.

For example, if you had ViewA with an @State property like this:

@State var showingNewUserView = false

You might present your NewUserView using a sheet, like this:

.sheet(isPresented: $showingNewUserView) {

Using the binding approach to dismissing, you would modify your target view – the one that was presented in a sheet – so that it has a binding of the same type used to present the view.

In our example above we presented the sheet when showingNewUserView was true, so we’d need to add a Boolean binding to NewUserView, like this:

@Binding var isPresented: Bool

When you want NewUserView to dismiss itself, you would just set isPresented back to false, like this:

self.isPresented = false

Now for the important part: when you create your target view (NewUserView, in this example), you need to pass in that binding as part of your initializer, so that Swift knows which Boolean it is working with.

So, you might replace your previous sheet code with this:

.sheet(isPresented: $showingNewUserView) {
    NewUserView(isPresented: self.$showingNewUserView)

Using this approach, SwiftUI will cause those two views to read and write the same Boolean value, which means when NewUserView sets the Boolean back to false it will hide the sheet automatically.

Save 50% in my Black Friday sale.

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.9/5

Link copied to your pasteboard.