1

I have 3 views: A (the main one), B and C. From ViewA one can navigate to either ViewB or ViewC, while B and C can only dismiss themselves, like in the "diagram" below:

  A
 / \ 
B   C

Depending on what happens in ViewB, I want to go back in ViewA and open ViewC. I tried sending the state var in ViewB as a binding.

NavigationLink(destination: B_View(locations: self.$showC), isActive: $showB) { EmptyView() }

This way, when I need to, I can toggle showC from within ViewB, with the following result:

  • View B is dismissed
  • View C is pushed and displayed
  • View C is dismissed, too :(

What should I do in order to keep ViewC from being dismissed automatically?

DarkByte
  • 1,162
  • 8
  • 17

1 Answers1

2

Here is a demo of possible solution. Prepared and tested with Xcode 12.4 / iOS 14.4.

The idea is to control navigation at the root view side, because changes in NavigationView internal state seems confused by moment of modification.

demo

class NavRouteModel: ObservableObject {
    @Published var currentTag: Int?
}

struct TestNavigationTriangle: View {
    @StateObject private var vm = NavRouteModel()
    
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink("ViewB", destination: ViewB {
                    self.vm.currentTag = 0
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        self.vm.currentTag = 2
                    }
                }, tag: 1, selection: $vm.currentTag)
                NavigationLink("ViewC", destination: Text("ViewC"), tag: 2, selection: $vm.currentTag)
            }
        }
    }
}

struct ViewB: View {
    var completed: () -> () = {}
    
    var body: some View {
        Button("Complete & Go to ViewC", action: completed)
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • So according to you answer, this [question](https://stackoverflow.com/questions/65914281/programmatic-navigation-with-navigationview-navigationlink-delay-jumps-back) has same problem, I am wondering why state is confused by that action, it looks like a bug? – egeeke Feb 14 '21 at 13:34