Search code examples
swiftswiftuiswiftui-navigationstack

Use NavigationPath across multiple views in SwiftUI


I'm new to Swift/SwiftUI, and I'm working with the NavigationStack view the programmatic way using a NavigationPath. Here is a part of my code:

struct ContentView: View {    
    @State private var path = NavigationPath()
    
    var body: some View {
        NavigationStack(path: $path) {
            List {                
                Section("Games") {
                    ForEach(Game.examples, id: \.name) { game in
                       NavigationLink(value: game) {
                         Text(game.name)
                       }
                    }
                }
            }
            .navigationTitle("Gaming")
            .navigationDestination(for: Game.self) { game in
                GameDetailView(game: game)
            }
        }
    }
}

Inside the GameDetailView, I'm trying to access path, like so:

struct GameDetailView: View {
    let game: Game
    
    var body: some View {
        VStack(spacing: 20) {
            Text("\(game.name) - Rating: \(game.rating)")
                .font(.largeTitle.bold())
            
            Button("Go home") {
                path.removeLast(path.count)
            }
        }
    }
}

My question is, how can I make path accessible in this file?

I've tried passing it down but that doesn't work, because it's not a binding I assume? I've thought about creating a class for this, but it seemed a bit of an overkill to me, but again, I'm new to Swift/SwiftUI.


Solution

  • GameDetailView(path: $path, game: game)
    ...
    
    struct GameDetailView: View {
        @Binding var path: NavigationPath
    ...