Skip to content
DeveloperMemos

Taking a Look at SwiftUI's dismiss()

SwiftUI, dismiss(), Navigation1 min read

When working with SwiftUI, navigation is an essential part of creating a seamless user experience. SwiftUI provides several tools and techniques to manage navigation, and one of them is the dismiss() function. In this article, we will take a closer look at SwiftUI's dismiss() function and explore how it can be used to dismiss views and navigate within an app.

What is dismiss()?

The dismiss() function is a SwiftUI modifier that allows us to dismiss a presented view or navigate back to the previous screen. It is primarily used in combination with modal presentations, such as presenting a sheet or a fullscreen modal view. By invoking dismiss(), we can remove the presented view from the screen and return to the previous view hierarchy.

Dismissing a Sheet

One common use case for dismiss() is to dismiss a sheet presentation. Let's consider an example where we have a button that presents a sheet when tapped:

1struct ContentView: View {
2 @State private var isPresentingSheet = false
3
4 var body: some View {
5 Button("Present Sheet") {
6 isPresentingSheet = true
7 }
8 .sheet(isPresented: $isPresentingSheet) {
9 SheetView()
10 }
11 }
12}
13
14struct SheetView: View {
15 @Environment(\.presentationMode) var presentationMode
16
17 var body: some View {
18 VStack {
19 Text("This is a sheet")
20 Button("Dismiss") {
21 presentationMode.wrappedValue.dismiss()
22 }
23 }
24 .padding()
25 }
26}

In the above example, we define a ContentView with a button that presents a sheet. The SheetView is presented as a sheet using the sheet(isPresented:content:) modifier. Inside the SheetView, we have a button labeled "Dismiss." When the button is tapped, we invoke dismiss() on the presentationMode environment variable, which dismisses the sheet and returns to the ContentView.

Dismissing a Fullscreen Modal View

Another scenario where dismiss() can be used is when presenting a fullscreen modal view. Let's take a look at an example:

1struct ContentView: View {
2 @State private var isPresentingModal = false
3
4 var body: some View {
5 Button("Present Modal") {
6 isPresentingModal = true
7 }
8 .fullScreenCover(isPresented: $isPresentingModal) {
9 ModalView()
10 }
11 }
12}
13
14struct ModalView: View {
15 @Environment(\.dismiss) var dismiss
16
17 var body: some View {
18 VStack {
19 Text("This is a modal view")
20 Button("Dismiss") {
21 dismiss()
22 }
23 }
24 .padding()
25 }
26}

In this example, we have a button in the ContentView that presents a fullscreen modal view when tapped. The ModalView is presented using the fullScreenCover(isPresented:content:) modifier. Inside the ModalView, we have a button labeled "Dismiss." When the button is tapped, we invoke the dismiss() function from the Environment to dismiss the fullscreen modal view and return to the ContentView.