Search code examples
swiftuiswiftui-navigationlink

SwiftUI - Navigating back to home without nesting?


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


Solution

  • 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")
       }
    }