为什么导航标题没有使用 SwiftUI 显示?

我正在使用苹果的官方教程学习 SwiftUI: Https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation

一切都很完美,直到我尝试通过调用 .navigationBarTitleNavigationView上显示导航标题。

我尝试刷新 live 视图,重新启动 Xcode,但它仍然没有显示出来。

我的原则是:

import SwiftUI


struct LandmarkList : View {
var body: some View {
NavigationView {
List(landmarkData) { landmark in
LandmarkRow(landmark: landmark)
}
}
.navigationBarItem(title: Text("Done"))
.navigationBarTitle(Text("Landmarks"))
}
}


#if DEBUG
struct LandmarkList_Previews : PreviewProvider {
static var previews: some View {
LandmarkList()
}
}
#endif

Xcode 看起来像这样:

Screenshot

根据教程,它应该显示导航标题,但是在我的例子中没有显示。

知道为什么吗,谢谢!

30012 次浏览

.navigationBarTitle() and .navigationBarItem() are modifiers on the View inside of the NavigationView, not on the NavigationView itself:

struct LandmarkList: View {
var body: some View {
NavigationView {
List(landmarkData) { landmark in
LandmarkRow(landmark: landmark)
}
.navigationBarItem(title: Text("Done"))
.navigationBarTitle(Text("Landmarks"))
}
}
}

and if you think about it, this makes sense. As the View within the NavigationView changes, the new View dictates what the title and contents of the navigation bar should be.

Description:

NavigationView is just a container around some content. Contents are changing when you navigating from page to page, but the NavigationView persists.

The point is that NavigationView shows each view's content when it shows it. So it will encapsulate with the destination.

Finally, you should add all navigation modifiers inside the navigation (on the content)


Example:

struct Content: View {
var body: some View {
Text("Some. content")
.navigationBarItem(title: Text("Done"))
.navigationBarTitle(Text("Landmarks"))
}
}
struct Parent: View {
var body: some View {
NavigationView {
Content() // This contains navigation modifiers inside the view itself
}
}
}

If someone is looking for navigation title with tab button, this code may be helpful -

struct ContentView: View {
var body: some View {
NavigationView {
Text("SwiftUI")
.navigationTitle("Screen Title")
.toolbar {
Button("Right") {
print("Right button tapped!")
}
}
}
}
}