How it works
PresentationMode is a structure that reports whether the view that owns it is currently presented, and gives that view a way to dismiss itself. SwiftUI publishes the active presentation through the environment, so a presented view can ask to be removed without holding a binding to whatever sheet, popover, or navigation push displayed it. Reach for it when a detail or modal view needs to close itself in response to a button tap or a completed task, rather than pushing that responsibility back up to the presenting view.
Read the presentation from the environment
PresentationMode is delivered through SwiftUI's environment under the presentationMode key, so you bring it in with the @Environment property wrapper rather than constructing it yourself. In the example,
@Environment(\.presentationMode) var presentationModebinds the current presentation to a property the view can consult and act on.Unwrap the binding with wrappedValue
The environment hands you a Binding<PresentationMode>, so you reach the structure itself through its
wrappedValue. The example writespresentationMode.wrappedValueto get the live PresentationMode value before doing anything with it, since the wrapper, not the property, holds the current state.Inspect isPresented to know your state
PresentationMode exposes an
isPresentedBoolean that is true while the view is on screen as part of a presentation. You can read it to drive conditional behavior — for instance, only running dismissal logic when the view is actually being presented — though the demo simply trusts that it is presented and offers a way out.Call dismiss() to remove the view
The structure's
dismiss()method asks SwiftUI to take the current view out of its presentation, closing the sheet or popping the navigation destination that showed it. The example wires this into a button so that tappingButton("Dismiss")runspresentationMode.wrappedValue.dismiss()and the screen closes itself.
Text(presentationMode.wrappedValue.isPresented ? "On screen" : "Dismissed") above the button to watch isPresented flip as dismiss() takes effect.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct PresentationModeDemo: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
VStack(spacing: 16) {
Text("Detail Screen")
.font(.headline)
Button("Dismiss") {
presentationMode.wrappedValue.dismiss()
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}