swiftuiswiftui-navigationlinkswiftui-navigationviewswiftui-navigationstack

navigate with NavigationStack


I am new to SwiftUI framework. I am trying to implement NavigationStack. I want to navigate on button action instead of using NavigationLink. The reason behind that is, I need to navigate once a particular function get performed on button action.

struct AView: View {
    @State private var actionss = [Int]()

    var body: some View {
        NavigationStack(path: $actionss) {
            VStack {
                Button("test") {
                    actionss.append(0)
                }
            }
            .navigationDestination(for: Int.self) { _ in
                BView()
            }
        }
    }
}

Above code of AView is working fine to navigate BView. The only thing is I am not able to navigate on CView from BView without using NavigationLink.

I need to perform particular function before navigate from BView to CView as well.


Solution

  • Assuming that the work is done on BView you can use .navigationDestination as well:

    struct AView: View {
        @State private var actionss  = [Int]()
    
        var body: some View {
    
            NavigationStack(path:$actionss) {
                VStack{
                    Button("show BView") {
                        actionss.append(0)
                    }
                }
                .navigationDestination(for: Int.self) { data in
                    BView()
                }
                .navigationTitle("AView")
            }
        }
    }
    
    struct BView: View {
    
        @State var show: Bool = false
    
        var body: some View {
    
            VStack {
                Button("show CView") {
                    show = true
                }
            }
            .navigationDestination(isPresented: $show) {
                CView()
            }
            .navigationTitle("BView")
        }
    }
    
    struct CView: View {
    
        var body: some View {
            Text("Hello")
                .navigationTitle("CView")
        }
    }