I want to have a navigation view with 3 views where the third view need to pop to the root view when button is clicked.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.