我试图在SwiftUI中以编程方式推送视图,但是当我使用NavigationLink的isActive属性推送两个视图时,最后一个视图被推送并立即弹出。 我不确定我是在做错什么还是SwuiftUI的错误。
这是我尝试推送两个视图时的外观:
如果我按一个视图,然后再按另一个视图,则它会起作用:
这是我的代码。我将appState作为EnvironmentObject传递
class AppState: ObservableObject {
@Published var showView1 = false
@Published var showView2 = false
}
struct ContentView: View {
@EnvironmentObject var appState: AppState
var body: some View {
NavigationView {
VStack {
Button(action: {
appState.showView2 = false
appState.showView1 = true
}) {
Text("Show view 1")
}
Button(action: {
appState.showView2 = true
appState.showView1 = true
}) {
Text("Show view 2")
}
NavigationLink( destination: View1(), isActive: $appState.showView1, label: { EmptyView() })
}
}
}
}
struct View1: View {
@EnvironmentObject var appState: AppState
var body: some View {
VStack {
Text("This is view1")
Button(action: {
appState.showView2 = true
}) {
Text("Show view2")
}
NavigationLink( destination: View2(), isActive: $appState.showView2, label: { EmptyView() })
}
}
}
struct View2: View {
@EnvironmentObject var appState: AppState
var body: some View {
VStack {
Text("This is view2")
Button(action: {
appState.showView1 = false
appState.showView2 = false
}) {
Text("Back to root")
}
}
}
}
这可能与https://stackoverflow.com/a/57274613/2584078
中描述的错误有关但是在这种情况下是相反的。弹出视图时插入了
我正在使用Xcode 12.0 beta 2(12A6163b)