ios – SwiftUI NavigationStack always pops to root


I have recently updated the navigation in my app from using lots of NavigationLinks, because I was seeing errors surrounding multiple pushes to the navigation stack.

My app is now working well with a custom navcontroller that programatically adds views to the stack, but there is one issue with when I try to pop back to the previous view using the back button on the toolbar it always pops all the way back to the root going through all the child views one by one.

Here is an overview of the current setup:

Navigation Controller –

class NavigationController: ObservableObject {

@Published var homeNavPath: [AppView] = []

public func navigateTo(destination: AppView) {
      homeNavPath.append(destination)
}

}

Navigation Stack –

 NavigationStack(path: $navController.homeNavPath) {
     HomeView()
 }

**Navigation Example – **

public struct HomeView: View {

    @EnvironmentObject var navController: NavigationController

    public var body: some View {
        Text("GO TO POST").onTapGesture {
            navController.navigateTo(PostView("123"))
        }
    }
}


public struct PostView: View {

    @EnvironmentObject var navController: NavigationController

    public var body: some View {
        Text("GO TO USER").onTapGesture {
            navController.navigateTo(UserView("123"))
        }
    }
}

public struct UserView: View {

    @EnvironmentObject var navController: NavigationController

    public var body: some View {
        Text("USER INFORMATION...")
    }
}

I am able to perfectly navigate from Home -> Post -> User as expected, but when I press the back button on the user page, it will always navigate back to the root (e.g home in this case) no matter how long the navigation path it.

Here is an example, I only press the back button once here:

example navigation gif

Let me know if there is any more information that could help and thanks for any suggestions

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img