The issue I'm facing is that my NavigationPath is always empty. The context is that I have 3 Views.
View A contains the NavigationStack and has two NavigationLinks, to View B and View C respectively.
View B has a NavigationLink to View C and a toolbar button to View A.
View C has a NavigationLink to View B and a toolbar button to View A.
struct ViewA: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
Text("ViewA")
NavigationLink {
ViewB(path: $path)
} label: {
Text("Go to ViewB")
}
NavigationLink {
ViewC(path: $path)
} label: {
Text("Go to ViewC")
}
}
}
}
struct ViewB: View {
@Binding var path: NavigationPath
var body: some View {
VStack {
Text("ViewB")
NavigationLink {
ViewC(path: $path)
} label: {
Text("Go to ViewC")
}
}
.toolbar {
Button("ViewA") {
path = NavigationPath()
}
}
}
}
struct ViewC: View {
@Binding var path: NavigationPath
var body: some View {
VStack {
Text("ViewC")
NavigationLink {
ViewB(path: $path)
} label: {
Text("Go to ViewB")
}
}
.toolbar {
Button("ViewA") {
path = NavigationPath()
}
}
}
}
Variable path is always empty.
I've tried multiple implementations, still not working. I'm expecting to have the toolbar button send me to View A.
You need to use the
valueparameter of theNavigationLinkin conjuction to thenavigationDestinationmodifier for the path State variable to be changed, or you could append objects that conform to theHashableprotocol to navigate (thenavigationDestinationis needed either way).Here's an example:
And here are
ViewBandViewC:When you append values to the path the
navigationDestinationcallback for the type appended gets called. It took me a bit to get it when I first saw it but now it is pretty straightforward. Let me know if you any doubts.