david dt
david dt

Reputation: 169

NavigationStack inside view of another NavigationStack

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()
    }
}

Upvotes: 10

Views: 2985

Answers (2)

Ale
Ale

Reputation: 21

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

Upvotes: 2

david dt
david dt

Reputation: 169

As mentioned in comments the nesting is the problem. I removed the nested NavigationStack which was "resetting" the original one so it didn't bounce back. I left the NavigationLinks in the child view which works fine.

Upvotes: -1

Related Questions