Categories
Swift SwiftUI

NavigationLink and presentationMode environment value property for dismissing a view in SwiftUI

How to navigate to a new view in SwiftUI and then dismissing it? Let’s set up a main view in NavigationView and NavigationLink for opening detail view. NavigationLink is a button triggering a navigation to a specified view. Detail view will contain a button for navigating back to the first view. But how do we dismiss presented detail view?

Reading environment and dismissing the detail view

SwiftUI provides a dynamic view property named Environment. It can be used for reading values from the view’s environment. Presentation mode is one of those values we can read. This is how we get access to PresentationMode structure what has isPresented property and function for dismissing the view. Therefore, we need to add dynamic view property to our detail view and then calling dismiss() when the button is tapped

import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
VStack(spacing: 8) {
Text("Hello World")
NavigationLink("Go to Detail View", destination: DetailView())
}.navigationBarTitle(Text("View 1"))
}
}
}
Content shown in navigation view
import SwiftUI
struct DetailView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
VStack(spacing: 8) {
Text("Detail view")
Button("Go Back", action: {
self.presentationMode.wrappedValue.dismiss()
})
}
}
}
Detail view with button for navigation back to the content view

Summary

SwiftUI has a dynamic view property Environment what we can use for getting more knowledge about the environment view is presented (locale, displayScale etc). One of the environment values is PresentationMode what we can use for dismissing the detail view.

If this was helpful, please let me know on Mastodon@toomasvahter or Twitter @toomasvahter. Feel free to subscribe to RSS feed. Thank you for reading.

One reply on “NavigationLink and presentationMode environment value property for dismissing a view in SwiftUI”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s