我是一个新的 Xcode/SwiftUI 程序员,我在我的 ThirdView 代码(如下)中遇到了一个问题,即完全相同的按钮代码作为尾随的 navigationBarItem 按预期工作,但当我移动按钮并关联时根本不出现代码到领先的酒吧项目点。下面的代码说明了这个问题。
此代码示例与我发布的上一个问题的代码几乎相同(一个非常有用的 StackOverflow 社区成员帮助我解决了这个问题);我在这里的问题涉及同一代码中的不同问题。
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")
} // End of NavigationView
} // End of body
} // End of ContentView
struct SecondView: View {
@Binding var active: Bool
@State private var thirdViewLink: Bool = false
var body: some View {
VStack {
Spacer()
NavigationLink(destination: ThirdView(thirdViewActive: $thirdViewLink),
isActive: $thirdViewLink) {
EmptyView()
} // End of NavigationLink
Spacer()
}.padding() // End of VStack
.navigationBarTitle("Second View")
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: Button("Back to 1st View") {
self.active = false
}, trailing: Button("Show Third View") {
self.thirdViewLink = true
}
)
} // End of body
} // End of SecondView
struct ThirdView: View {
@Binding var thirdViewActive: Bool
var body: some View {
VStack(spacing: 15) {
Text("Third View")
Spacer()
}.padding() // End of VStack
.navigationBarBackButtonHidden(true)
//The following approach does NOT work
.navigationBarItems(leading: Button("Back to 2nd View") {
self.thirdViewActive = false
})
// This DOES work - why the difference?
/* .navigationBarItems(trailing: Button("Back to 2nd View") {
self.thirdViewActive = false
}) */
} // End of body
} // End of ThirdView
为什么“返回第二个视图”的 ThirdView 按钮仅在我将其分配给尾随 navigationBarItems() 位置时出现?在这种情况下,如何使按钮出现在前导位置?非常感谢您提供的任何见解!