0

I want to have a navigation view with 3 views where the third view is poping to the root. I've read this thread and there I thought that this way implemented below could be the best way to achieve this, because it looked easier. Here is the code I'm implementing:

import SwiftUI

class NavigationHelper: ObservableObject {
    @Published var selection:String? = nil
}

struct View1: View {
    
    @ObservedObject var navigationHelper:NavigationHelper = NavigationHelper()
    
    var body: some View {
        NavigationView{
            VStack {
                Text("View1")
                    .padding()
                
                Button {
                    navigationHelper.selection = "View2"
                } label: {
                    Text("Go To View2")
                }

                
                NavigationLink(tag: "View2", selection: $navigationHelper.selection) {
                    View2()
                } label: {
                    EmptyView()
                }.isDetailLink(false)
            }
        }.environmentObject(navigationHelper)

    }
}

struct View2: View {
    @EnvironmentObject var navigationHelper:NavigationHelper
    
    var body: some View {
        VStack {
            Text("View2")
                .padding()
            
            Button {
                navigationHelper.selection = "View3"
            } label: {
                Text("Go To View3")
            }
            
            
            NavigationLink(tag: "View3", selection: $navigationHelper.selection) {
                View3()
            } label: {
                EmptyView()
            }
        }
    }
}


struct View3: View {
    @EnvironmentObject var navigationHelper:NavigationHelper
    
    var body: some View {
        VStack {
            Text("View3")
                .padding()
            
            Button {
                navigationHelper.selection = nil
            } label: {
                Text("Go To Root")
            }
        }
    }
}

When View3 is opened it pops back to View1 when opened and cannot understand why? For some reason the selection property becomes nil maybe.

Foriger
  • 459
  • 5
  • 30

0 Answers0