Home > Enterprise >  NavigationLink inside popover that changes main view
NavigationLink inside popover that changes main view

Time:10-15

I would like to have a NavigationLink inside a popover that changes the popover's root view, but I can't find a way to make it work.

With the following code, the view that changes is the popover itself. However, if I remove the popover's NavigationStack the NavigationLink goes disabled.

struct View1 : View {
    
    @State var popoverActive = false
    
    var body: some View {
        NavigationStack {
            Text("View1")
            
            Button(action: {popoverActive.toggle()}) {
                Text("Popover")
            }.popover(isPresented: $popoverActive) {
                PopOverView()
            }
        }
    }
}


struct PopOverView : View {
    var body: some View {
        NavigationStack {
            NavigationLink(value: 1) {
                Text("Go to View 2")
            }
            .navigationDestination(for: Int.self) { i in
                View2()
            }
        }
    }
}

struct View2 : View {
    var body: some View {
        Text("View 2")
    }
}

CodePudding user response:

You can use the path with your NavigationStack and add navigationDestination in your View1 like this.

struct View1: View {
    @State var path = NavigationPath()
    @State var popoverActive = false
    
    var body: some View {
        NavigationStack(path: $path) {
            VStack {
                Text("View1")
                
                Button(action: {popoverActive.toggle()}) {
                    Text("Popover")
                }.popover(isPresented: $popoverActive) {
                    PopOverView() {
                        popoverActive = false
                        path.append(2)
                    }
                }
            }
            .navigationDestination(for: Int.self) { i in
                View2()
            }
        }
    }
}

PopOverView

struct PopOverView : View { 
    var showSecondView: ()->()
    
    var body: some View {
        Button("Go to View 2") {
            showSecondView()
        }
    }
}
  • Related