I'd like to navigate from View2Test
to View3Test
through RouterTest
.
I wrote the demo code the way I solved it.
My question is why I need to use DispatchQueue.main.asyncAfter(deadline: .now() + 0.5)
to prevent View3Test
from closing after it is opened or is there a better way?
import SwiftUI
class RouterStore: ObservableObject {
static let shared = RouterStore()
@Published var showView1: Bool = false
@Published var showView3: Bool = false
}
struct RouterTest: View {
@ObservedObject var store = RouterStore.shared
var body: some View {
NavigationView {
VStack {
Text("RouterTest")
Button(
action: { self.store.showView1 = true },
label: { Text("Go to View1") }
)
NavigationLink(
destination: LazyView {
View3Test()
},
isActive: $store.showView3,
label: { EmptyView() }
)
NavigationLink(
destination: LazyView {
View1Test()
},
isActive: $store.showView1,
label: { EmptyView() }
)
.isDetailLink(false)
.onDisappear {
print("RouterTest onDisappear NavigationLink")
}
}
}
.onDisappear {
print("RouterTest onDisappear")
}
}
}
struct View1Test: View {
@ObservedObject var store = RouterStore.shared
var body: some View {
VStack {
Text("View1Test")
NavigationLink(
destination: LazyView {
View2Test()
},
label: { Text("Go to View2") }
)
}
}
}
struct View2Test: View {
@ObservedObject var store = RouterStore.shared
var body: some View {
VStack {
Text("View2Test")
Button(
action: {
self.store.showView1 = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.store.showView3 = true
}
},
label: { Text("Go to RouterTest") }
)
}
}
}
struct View3Test: View {
@ObservedObject var store = RouterStore.shared
var body: some View {
VStack {
Text("View3Test")
}
}
}
Without DispatchQueue.main.asyncAfter(deadline: .now() + 0.5)