I have three views A,B and C. User can navigate from A to B and from A to C. User can navigate from B to C. Now I want to differentiate if the user have come from A to C or from B to C so I was looking in how to pass extra data in NavigationStack which can help me differentiate
Below is my code
import SwiftUI
@main
struct SampleApp: App {
@State private var path: NavigationPath = .init()
var body: some Scene {
WindowGroup {
NavigationStack(path: $path){
A(path: $path)
.navigationDestination(for: ViewOptions.self) { option in
option.view($path)
}
}
}
}
enum ViewOptions {
case caseB
case caseC
@ViewBuilder func view(_ path: Binding<NavigationPath>) -> some View{
switch self{
case .caseB:
B(path: path)
case .caseC:
C(path: path)
}
}
}
}
struct A: View {
@Binding var path: NavigationPath
var body: some View {
VStack {
Text("A")
Button {
path.append(SampleApp.ViewOptions.caseB)
} label: {
Text("Go to B")
}
Button {
path.append(SampleApp.ViewOptions.caseC)
} label: {
Text("Go to C")
}
}
}
}
struct B: View {
@Binding var path: NavigationPath
var body: some View {
VStack {
Text("B")
Button {
path.append(SampleApp.ViewOptions.caseC)
} label: {
Text("Go to C")
}
}
}
}
struct C: View {
@Binding var path: NavigationPath
var body: some View {
VStack {
Text("C")
}
}
}
ViewOptionsto represent all views in the path (including view A) you could use an array of[ViewOptions]instead of a NavigationPath object, and that would allow you to interoogate your hierarchy? i.e., the last item in the array is your current view, but the second-to-last will be the view before that.ViewOptionsstruct, you can declare@State var path: [ViewOptions]instead of using a NavigationPath object. If you do this, then you can look inside that array to see the objects that make up the current path. NavigationPath has a few collection-liek methods, but you can't look inside it in the same way as you can with arrays.