我想在 SwiftUI 中初始化一个导航堆栈。因此,我想在第一个视图出现后立即推送第二个视图。因此,我想使用一个@State var,我将其设置为 true onAppear,从而激活 NavigationLink。
但是,该方法不起作用(未经修改,请参见下文)。推送完成,然后立即关闭第二个视图(视频)。这是我的示例(Github Repo):
struct SecondView: View {
var body: some View {
Text("Second")
.navigationTitle("Second")
.onAppear(perform: {
print("Second: onAppear")
})
}
}
struct FirstView: View {
@State var linkActive = false
var body: some View {
NavigationLink(destination: SecondView(), isActive: $linkActive) {
Text("Goto second")
}
.navigationTitle("First")
.onAppear(perform: {
print("First: onAppear")
linkActive = true
})
.onChange(of: linkActive) { value in
print("First: linkActive changed to: \(linkActive)")
}
}
}
struct SwiftUIView: View {
var body: some View {
NavigationView {
NavigationLink(destination: FirstView()) {
Text("Goto first")
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
输出:
First: onAppear
First: linkActive changed to: true
Second: onAppear
First: linkActive changed to: false
如果我在延迟一分钟后修改 onAppear 以将 linkActive 设置为 true。0.5秒就可以了。这里有什么问题?我希望 SecondView 留在屏幕上,因为我不明白为什么 isActive 被改回 false。