[英]Why The Navigation Title doesn't show up using SwiftUI?
我正在使用苹果官方教程学习SwiftUI
: https ://developer.apple.com/tutorials/swiftui/building-lists-and-navigation
一切正常,直到我尝试通过调用.navigationBarTitle
在NavigationView
上显示导航标题。
我试图刷新实时视图,重新启动 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 看起来像这样:
根据教程,它应该显示导航标题,但在我的情况下没有。
知道为什么吗? 谢谢!
.navigationBarTitle()
和.navigationBarItem()
是NavigationView
内部View
的修饰符,而不是NavigationView
本身:
struct LandmarkList: View {
var body: some View {
NavigationView {
List(landmarkData) { landmark in
LandmarkRow(landmark: landmark)
}
.navigationBarItem(title: Text("Done"))
.navigationBarTitle(Text("Landmarks"))
}
}
}
如果你仔细想想,这是有道理的。 随着NavigationView
中的View
发生变化,新的View
决定了导航栏的标题和内容应该是什么。
NavigationView
只是围绕某些内容的容器。 当您从一个页面导航到另一个页面时,内容会发生变化,但NavigationView
仍然存在。
关键是NavigationView
在显示每个view
时会显示它的内容。 所以它将与目的地封装在一起。
最后,您应该在导航内(在内容上)添加所有导航修饰符
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
}
}
}
如果有人正在寻找带有标签按钮的导航标题,此代码可能会有所帮助 -
struct ContentView: View {
var body: some View {
NavigationView {
Text("SwiftUI")
.navigationTitle("Screen Title")
.toolbar {
Button("Right") {
print("Right button tapped!")
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.