avatar
Published on

How to force navigation bar to show background in SwiftUI?

Authors
  • avatar
    Name
    Mick MacCallum
    Twitter
    @0x7fs

When using a NavigationStack, by default you'll only see the background of the navigation bar fade in if your content is wrapped in a ScrollView and you start scrolling. If you don't have a ScrollView this can lead to your navigation buttons appearing to float above your content, not in a navigation bar. If this is undesirable, use the toolbarBackground modifier and set the visibility parameter to .visible, instead of the default .automatic.

struct ContentView: View {
    var body: some View {
        NavigationStack {
            List {
                // ...
            }
            .toolbarBackground(.visible, for: .navigationBar)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    ShareLink(
                        item: URL(string: "https://bleepingswift.com")!
                    )
                }
            }
        }
    }
}

Here's a before and after screenshot of how this looks.

Before and after shot showing a transparent nav bar and an opaque one