我是一名新手 Xcode/SwiftUI 开发人员,一直被以下与导航相关的问题所困扰。在以下最小的、可重现的示例中,我希望用户能够在到达 ThirdView 后逐个浏览应用程序视图,如下所示:ThirdView -> SecondView -> FirstView(或 ContentView,在下面的示例中)。
当 SecondView 中到达 ThirdView 的 NavigationLink 位于 SecondView 的主体中时,一切都按预期工作。(这是我在下面的示例中注释掉的 SecondView 代码。)但是,如果我将相同的 NavigationLink 移动到导航栏(如图所示),单击 ThirdView 中的“返回到第二个视图”栏按钮不会执行任何操作. 观点不变。有没有办法通过栏按钮中的导航链接从 SecondView -> ThirdView 导航,但仍然能够从 ThirdView -> SecondView 向后前进?
我已经在网上阅读了一些对此类问题的问答,这些问题表明这个问题是 Xcode 模拟器中的一个小故障,但是当我在我的设备上加载应用程序时,我遇到了同样的问题。
struct ContentView: View {
@State private var activeLink: Bool = false
var body: some View {
NavigationView {
VStack {
Spacer()
NavigationLink("Show Second Screen",
destination: SecondView(active: $activeLink), isActive: $activeLink)
Spacer()
}.padding()
.navigationBarTitle("First view")
}
}
}
struct SecondView: View {
@Binding var active: Bool
@State private var thirdViewLink: Bool = false
var body: some View {
VStack {
Spacer()
// This works as expected but is not ideal for my purposes
/* NavigationLink("Show Third View",
destination: ThirdView(thirdViewActive: $thirdViewLink), isActive: $thirdViewLink) */
Spacer()
}.padding()
.navigationBarTitle("Second View")
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: Button("Back to 1st View") {
self.active = false
}, trailing: NavigationLink("Show Third View",
destination: ThirdView(thirdViewActive: $thirdViewLink),
isActive: $thirdViewLink))
}
}
struct ThirdView: View {
@Binding var thirdViewActive: Bool
var body: some View {
VStack(spacing: 15) {
Text("Third View")
Spacer()
}.padding()
.navigationBarItems(leading: Button("Back to 2nd View") {
self.thirdViewActive = false
})
}
}