Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why The Navigation Title doesn't show up using SwiftUI?

Tags:

ios

swift

swiftui

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:

Screenshot

According to the tutorial, it should show the navigation title but it doesn't in my case.

Any idea why? Thanks!

like image 316
Yiming Dong Avatar asked Jun 19 '19 01:06

Yiming Dong


2 Answers

.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.

like image 66
vacawama Avatar answered Sep 20 '22 18:09

vacawama


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         }     } } 
like image 36
Mojtaba Hosseini Avatar answered Sep 23 '22 18:09

Mojtaba Hosseini