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:
Let me know if there is any more information that could help and thanks for any suggestions
AppView? Do you get the same effect ifhomeNavPathis set to aNavigationPath()object? In my experience, using an array of custom objects as a path is best used for objects that you use with values (e.g.NavigationLink(value: ...) { }and.navigationDestination(for: ...). If you want to push views but have the control that a stateful stack gives you,NavigationPath()might be the way to go.