Search code examples
iosswiftswiftuiswiftui-navigationviewswiftui-navigationstack

SwiftUI: Displaying the navigation bar using NavigationStack


I want to display a navigation bar having an orange background color and a title with white color.

Everything works fine with this setup:

    let navigationBarAppearance = UINavigationBarAppearance()
    navigationBarAppearance.titleTextAttributes = [.foregroundColor: UIColor(Color.white)]
    navigationBarAppearance.backgroundColor = .orange
    
    UINavigationBar.appearance().standardAppearance = navigationBarAppearance
    UINavigationBar.appearance().compactAppearance = navigationBarAppearance
    UINavigationBar.appearance().scrollEdgeAppearance = navigationBarAppearance

And the source code for my screen looks like this:

struct ScreenView: View {
    var body: some View {
        NavigationView {
            List {
                NavigationLink("Row", destination: Text("Tapped on row"))
            }
        }
        .navigationTitle("List")
        .navigationBarTitleDisplayMode(.inline)
    }
}

The result:

enter image description here

If I replace the NavigationView with a NavigationStack, the navigation bar disappears.

Is there something that I miss?


Solution

  • You have to apply your .navigationTitle() modifier to views that are inside of NavigationStack:

        NavigationStack {
            List {
                NavigationLink("Row", destination: Text("Tapped on row"))
            }
            .navigationTitle("List")
            .navigationBarTitleDisplayMode(.inline)
        }
    

    That seems to fix that problem.