Dismiss a Modal View in SwiftUI
Written by Team Kodeco
Modal views in SwiftUI can be dismissed by the user through interactive gestures or a dismiss button you’ve added. However, there are times when you might need to dismiss the modal programmatically from your code. This entry will guide you on how to do that.
Let’s start with a simple scenario: a modal view that can be dismissed by tapping a Dismiss button:
struct ModalView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
Text("This is a modal view")
Button("Dismiss") {
dismiss()
}
}
}
}
struct ContentView: View {
@State private var isShowingModal = false
var body: some View {
Button("Show Modal") {
isShowingModal = true
}
.sheet(isPresented: $isShowingModal) {
ModalView()
}
}
}
Tap the Show Modal button and your preview should look like:
Now tap the Dismiss button to programatically dismiss the modal!
In the code above, the ModalView
is presented as a modal view using the sheet
modifier when a button is tapped.
Inside the ModalView
, you’re utilizing the @Environment
property wrapper to access the dismiss
environment value. dismiss
is an action that you can call to dismiss the current presentation.
When the Dismiss button is tapped, you simply call dismiss()
. This triggers SwiftUI to dismiss the modal view.
Please note that it’s important to define the dismiss
action in the appropriate environment. For example, it must be defined within the modal view that you intend to dismiss, not in the parent view that presents the modal view. If you define it in the wrong place, the dismissal action may not work as expected.
With the dismiss
environment value, SwiftUI makes it easy to dismiss views programmatically, which is a commonly used feature in many apps.