[英]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.