Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NavigationStack inside view of another NavigationStack

Tags:

swiftui

It seems like the NavigationStack with a path parameter interferes with the NavigationStack of a child view. I can't get this simple code to work. When you first tap on the NavLink it bounces back to the root view and the second time I click the link it jumps to the end (skips the first child view). How do I keep both NavigationStacks from interfering with each other?

import SwiftUI

struct TestView: View {
    //@EnvironmentObject var profile: Profile
    var testArr: [String] = ["one","Two"]
    @State private var navPath: [String] = []
    
var body: some View {
    NavigationStack(path: $navPath) {
        List(testArr, id: \.self) { testClass in
            NavigationLink(testClass.description, value: testClass)
        }.navigationDestination(for: String.self) { a in
            TestDetailView2()
        }
    }
    }
}

struct TestDetailView2: View {
    @State var navPath: [String] = []
    
    var body: some View {
        VStack {
            Text("First Child View")
            NavigationStack(path: $navPath) {
                VStack {
                    NavigationLink("Nested Nav", value: "Nav")
                }.navigationDestination(for: String.self) { a in
                    Text("Nested")
                }
                }
            }
        }
    }

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}
like image 340
david dt Avatar asked Apr 10 '26 15:04

david dt


1 Answers

I would remove the NavigationStack from the child view. In the child view change:

@State var navPath: [String] = []

to

@Binding var navPath: [String]

then pass the path to TestDetailView2

TestDetailView2(navPath: $navPath)

Also if your child view is on a different file, you'll need to wrap the returned view of the preview on its own NavigationStack if you want to preview it on its own

like image 143
Ale Avatar answered Apr 14 '26 00:04

Ale