SwiftUI: Navigating back to previous view after actions

Sometimes we want to navigate to the previous view after some actions are performed. For example, I was writing some code to implement a feature which should have the following flow: the user writes some data, then clicks on a “save button”, at this point the app should save the data and then goes back to the previous view.

It is easy to do so in Swift UI. What we need is an Environment variable in our view struct, exactly like this:

@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

Then, after performing the action, we need to call

self.presentationMode.wrappedValue.dismiss() 

This tells the view to dismiss itself, and therefore we will go back to the previous view before we entered the current view.

Leave a ReplyCancel reply