I am learning SwiftUI
using apple's official tutorial: https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation
Everything works perfectly until I try to show navigation title on an NavigationView
by calling .navigationBarTitle
.
I have tried to refresh the live view, restart Xcode, but it still doesn't show up.
here is my code:
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
The Xcode looks like this:
According to the tutorial, it should show the navigation title but it doesn't in my case.
Any idea why? Thanks!
.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.
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)
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With