How to navigate to any view inside of a NavigationView

497 views Asked by At

I have these 3 different views they all connect to each other through a NavigationView. I am trying to find a way to navigate to a page earlier in the NavigationView but I want the transition to seem like it is going backwards.

struct Testing: View {
    
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination:testing2()) { Text("Go to two") }
            }
            .navigationBarTitle("Navigation")
        }
    }
}

struct testing2 : View {

    var body: some View{
        VStack {
            NavigationLink(destination: testing3()) { Text("Go to third") }
        }
        .navigationBarTitle("Second Page")
    }
}

struct testing3 : View {

    var body: some View{
        VStack {
            Text("Go back to first")
        }
        .navigationBarTitle("Third Page")
    }
}

I have found a solution for this using a combination of an Observable Object, an Environment variable and tags and selections on the NavigationLink.

Is their a simpler solution to making the navigation transition go to a specific page and if it is a view that is before the current view preform the backwards transition?

2

There are 2 answers

3
Khashayar On

Much simpler solution is to modify your third view as following:

struct testing3 : View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    
    var body: some View{
        VStack {
            Button(action: {
                self.presentationMode.wrappedValue.dismiss()
                self.presentationMode.wrappedValue.dismiss()
            }) {
                Text("Go back to first")
            }
            
        }
        .navigationBarTitle("Third Page")
    }
}
0
dzren12 On

A basic workaround is to add a @Binding and pass it along. check the binding index on appear. if it's not the index presentation.wrappedValue.dismiss until it is. A more complicated way is to add a Navigator class that handles all navigation logic.