Search code examples
swiftuinavigationnavigationviewswiftui-navigationlink

Multiple NavigationView in a screen


I've 2 NavigationView in a screen. When I tap a Go To ChildView item on list, I want to navigate in Parent Navigation. When I tap a one of other items on list, I want to navigate in Container Navigation

How can I push a view to selected NavigationView ? I want to decide from which navigation to push the view.

enter image description here

Parent View

struct Parent: View {
    var body: some View {
    
    NavigationView { // Parent Navigation
        VStack {
            SearchBarView()
            ContainerView() // Container
        }
        .navigationTitle("Parent Navigation")
    }
}}

Container View

struct ContainerView: View {
    var body: some View {
    NavigationView { // Container Navigation
        List(0..<20) { i in
            
            if i == 0 {
                Text("Go To Child View")
            } else {
                NavigationLink(
                    destination: ChildView(),
                    label: {
                        Text("Text \(i)")
                    })
            }
            
        }
        .navigationTitle("Container Navigation")
        .navigationBarTitleDisplayMode(.large)
    }
}}

Solution

  • You need to place navigation link outside of internal navigation view, ex. in background, like shown below, and activate it programmatically.

    struct ContainerView: View {
        @State private var isActive = false
        var body: some View {
            NavigationView { // Container Navigation
                List(0..<20) { i in
    
                    if i == 0 {
                        Button("Go To Child View") {
                            isActive = true           // << here !!
                        }
                    } else {
                        NavigationLink(
                            destination: ChildView(),
                            label: {
                                Text("Text \(i)")
                            })
                    }
    
                }
                .navigationTitle("Container Navigation")
                .navigationBarTitleDisplayMode(.large)
            }
            .background(
                NavigationLink(                 // << here !!
                    destination: ChildView(),
                    isActive: $isActive,
                    label: { EmptyView() })
            )
        }
    }