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

IosSwiftSwiftui

Ios Problem Overview


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!

Ios Solutions


Solution 1 - Ios

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

Solution 2 - Ios

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYiming DongView Question on Stackoverflow
Solution 1 - IosvacawamaView Answer on Stackoverflow
Solution 2 - IosMojtaba HosseiniView Answer on Stackoverflow