NEW: Join my free 100 Days of SwiftUI challenge today! >>

How to make a view dismiss itself

Paul Hudson    @twostraws   

Fully updated for Xcode 11 GM

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:

self.presentationMode.wrappedValue.dismiss()

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) {
    NewUserView()
}

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.

LEARN SWIFTUI FOR FREE I have a massive, free SwiftUI video collection on YouTube teaching you how to build complete apps with SwiftUI – check it out!

Similar solutions…

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

Was this page useful? Let us know!