10

I'm having following trouble using NavigationView in SwiftUI.

I have a NavigationView embed in a TabView as follow:

var body: some View {
   TabView {
      NavigationView {
         View1()
      }
         .tabItem { Text("View 1") }
         .tag(1)
      View2()
         .tabItem {Text("View 2") }
         .tag(2)
   }
}

On the first tab, I have push several views to the NavigationView, but when switch to the second tab and then switch back to the first tab, the NavigationView become View1() again, all pushed views are erased. Demonstrated as bellow:

Step By Step

Expected behaviour is when switching to the first tab, the Payment view is showed instead of HomePage.

Is there anyway to put the state of NavigationView to an external @EnvironmentObject, for example, so that the state of NavigationView remain the same after switching.

Daniel Tran
  • 6,083
  • 12
  • 25
  • 3
    Can check this answer: https://stackoverflow.com/questions/57772137/tabview-resets-navigation-stack-when-switching-tabs – Binh Le Oct 11 '19 at 07:03

1 Answers1

-2

Yes there is a pretty easy way of using an state with an NavigationLink. There is a optional property isActive you give an @Binding variable, which also can be from an external Environment object using a @Published property inside the observable object. In Case you want to learn a bit more about SwiftUI NavigationView including the Navigation Link consider checking out this awesome video by Paul Hudson. It personally helped me a lot.

Moritz Schaub
  • 91
  • 1
  • 9