Back to Root View — Pure SwiftUI for iOS 16 With NavigationStack & NavigationDestination

jason19970210
2 min readMar 16, 2023

Photo by Shubham Dhage on Unsplash

Since the NavigationView has been soft deprecated for iOS 16 (detail), there comes 2 new instances: NavigationStack & NavigationSplitView . This also brings the new navigationDestination function for changing views.

The isActive argument for NavigationLink method is also deprecated (detail), so how can we changing the views by using NavigationStack & navigationDestination for the simplest way ?

Here is the migration document from apple: https://developer.apple.com/documentation/swiftui/migrating-to-new-navigation-types

For my case, there are 3 views: HomeView, FormView, PreviewView. The user will go through one another then pop back to HomeView by pressing a button.

Expectation:

Expectation Flow

By searching days and nights from anywhere I can reach, I cannot find any tutor or example which suit for my case. At the first time I am using navigationDestination , I tried using isPresented argument for controlling when the application should change view, such as button action, or some conditions. Along the method, the application didn’t pop back at the end of the flow.

So here is my solution, let’s dive into the code.

NavigationStack & navigationDestination Implementation from gist

First we create and initialize a global observed environment object goes with class Router, then share the router state for all views.

By using the new NavigationStack, here I called a .navigationDestination instance method with for parameter which make program control which destination as the ViewFactory class does.

Update ( 2023/03/16 ): modify the ViewFactory from class to enum without return AvyView().

But even the for parameter can solve the case, I am still wondering how to make this happened by using the isPresented parameter, here is the stackoverflow post discuss about this topic.

< Update 2023/04/12 >
Since the Xcode has been updated to Version 14.3 which supporting iOS 16.4 & iPadOS 16.4, I have encountered a new error message but the functions works great.
( ref: https://stackoverflow.com/a/75713254 )

Update NavigationAuthority bound path tried to update multiple times per frame.

Hope this article can help !

Sign up to discover human stories that deepen your understanding of the world.

jason19970210
jason19970210

Written by jason19970210

a slashie from Taiwan 🇹🇼! Fields: Software Dev, Networking, Digital Forensics Investigator, SA, UIUX, 3D Design, etc.

Responses (1)

Write a response