0

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?

iOSdeveloper
  • 103
  • 11

2 Answers2

4

Using SwiftUI only and NavigationStack, you can achieve a white title text on an orange background, with this code.

struct ScreenView: View {
    var body: some View {
        NavigationStack {
            List(0..<50, id: \.self) { _ in
                NavigationLink("Row", destination: Text("Tapped on row"))
            }
            .toolbar {
                ToolbarItem(placement: .principal) { Text("List").foregroundColor(.white) }
            }
            .navigationBarTitleDisplayMode(.inline)
            .toolbarBackground(.visible, for: .navigationBar)
            .toolbarBackground(Color.orange, for: .navigationBar)
        }
    }
}

struct ContentView: View {
    var body: some View {
        ScreenView()
    }
}
sumida
  • 268
  • 9
  • Thank your for your answer! If I scroll down the list, that orange background is expanding and it's not exactly what I am looking for. – iOSdeveloper Apr 28 '23 at 10:50
  • If I scroll down the list, that orange background is **not** expanding as you mentioned. I have updated my answer to show that the `orange` background does not expand when you scroll down the list. – sumida Apr 28 '23 at 22:53
  • now it works as expected. Thank you for updating your answer! – iOSdeveloper Apr 29 '23 at 11:14
2

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.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
krzysztofk
  • 36
  • 2