In terms of your first question (going from C
to A
), this is often called "popping to root" and has a number of solutions here on SO, including: https://mcmap.net/q/134166/-how-can-i-pop-to-the-root-view-using-swiftui
Your second question (replacing A
with C
as the root view) is a little different. You can do that by replacing A
with C
in the view hierarchy. In order to do this, you'd need to have some way to communicate with the parent view -- I chose a simple @State
/@Binding
to do this, but one could use an ObservableObject
or even callback function instead.
enum RootView {
case A, C
}
struct ContentView : View {
@State private var rootView : RootView = .A
var body: some View {
NavigationView {
switch rootView {
case .A:
ViewA(rootView: $rootView)
case .C:
ViewC(rootView: $rootView)
}
}.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ViewA : View {
@Binding var rootView : RootView
var body: some View {
VStack {
Text("View A")
NavigationLink(destination: ViewB(rootView: $rootView)) {
Text("Navigate to B")
}
}
}
}
struct ViewB : View {
@Binding var rootView : RootView
var body: some View {
VStack {
Text("View B")
NavigationLink(destination: ViewC(rootView: $rootView)) {
Text("Navigate to C")
}
Button(action: {
rootView = .C
}) {
Text("Navigate to C as root view")
}
}
}
}
struct ViewC : View {
@Binding var rootView : RootView
var body: some View {
VStack {
Text("View C")
switch rootView {
case .A:
Button(action: {
rootView = .C
}) {
Text("Switch this to the root view")
}
case .C:
Text("I'm the root view")
}
}
}
}