我想从 导航View2Test
到View3Test
through RouterTest
。
我以解决问题的方式编写了演示代码。
我的问题是为什么我需要使用它DispatchQueue.main.asyncAfter(deadline: .now() + 0.5)
来防止View3Test
打开后关闭或者有更好的方法?
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")
}
}
}
没有DispatchQueue.main.asyncAfter(deadline: .now() + 0.5)