3

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) { data 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. Please help me in this.

Thank you in advance.

  • This might help https://stackoverflow.com/questions/73723771/navigationstack-not-affected-by-environmentobject-changes – Nirav D Sep 29 '22 at 15:24
  • Does this answer your question? [Make Custom SwiftUI Views with ObservedObjects compatible with NavigationLink iOS 16](https://stackoverflow.com/questions/73696898/make-custom-swiftui-views-with-observedobjects-compatible-with-navigationlink-io) – Andre Oct 14 '22 at 01:31

1 Answers1

3

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")
    }
}
Carsten
  • 581
  • 4
  • 17
  • im using a button and the navigation destination, but im getting the view Below the NavigationBar with another navigationBar... in presented view there's no navigationStack so there shouldn't be another navigation bar below the parent one, Can anyone point me in where to look for the bug ? – lorenzo gonzalez Jul 12 '23 at 14:24
  • already found my bug.. I had a motherView routing to the homeView or Login View, but all of that was also wrapped in a NavigationView, while on the homeView I was using a NavigationStack... , do not mix between them ;) . had to change in the mother view to navigationStack and did fix – lorenzo gonzalez Jul 12 '23 at 14:31