SwiftUI - Navigating back to home without nesting?

423 views Asked by At

In the code below, if I use the links to go back and forth between views A and B, I will end up with nested views as shown in the image. The only way I've found to avoid nesting is to never link to a view where a NavigationView is declared - as it is in ViewA below. My question...is there any way to go back to ViewA without the views nesting?

struct ViewA: View {
   var body: some View {
      NavigationView{
        NavigationLink(destination: ViewB()) {
           Text("ViewB")
        }
      }
      .navigationBarTitle("ViewA")
   }
}

struct ViewB: View {
   var body: some View {
       NavigationLink(destination: ViewA()) {
          Text("ViewA")
       }
      .navigationBarTitle("ViewB")
   }
}

enter image description here

2

There are 2 answers

5
Asperi On BEST ANSWER

You should not create NavigationLink(destination: ViewA()) because it is not back it creates a new ViewA. Once you navigate to ViewB, the back button will be create for you automatically.

struct ViewA: View {
   var body: some View {
      NavigationView{
        NavigationLink(destination: ViewB()) {
           Text("ViewB")
        }
      }
      .navigationBarTitle("ViewA")
   }
}

struct ViewB: View {
   var body: some View {
      Text("ViewB Pure Content")
         .navigationBarTitle("ViewB")
   }
}
0
dzren12 On

You are nesting views because every time you click ViewA/ViewB it creates a new view object. You can add

@Environment(\.presentationMode) var presentationMode and call presentationMode.wrappedValue.dismiss()

when the view button gets pressed you dismiss it.