SwiftUI: how to change NavigationView.toolbar background color

Viewed 6156

Any idea on how to apply a specific background color to the bottom toolbar?

NavigationView {
    List {
        ....
    }
    .toolbar {
        ToolbarItem(placement: .bottomBar) {
            Button(action: { model.selectTab(tab: "ITEM1") }, label: { Text("ITEM1") })
        }
        ToolbarItem(placement: .bottomBar) {
            Button(action: { model.selectTab(tab: "ITEM2") }, label: { Text("ITEM2") })
        }
        ToolbarItem(placement: .bottomBar) {
            Button(action: { model.selectTab(tab: "ITEM3") }, label: { Text("ITEM3") })
        }
    }
}
4 Answers

You can do this using UIToolbar appearance. Tested with Xcode 12 / iOS 14.

demo

struct DemoView: View {
    
    init() {
        UIToolbar.appearance().barTintColor = UIColor.red
    }
    
    var body: some View {
        NavigationView {
            List {
                Text("Item")
            }
            .toolbar {
                ToolbarItem(placement: .bottomBar) {
                    Button(action: { }, label: {Text("ITEM1")})
                }
                ToolbarItem(placement: .bottomBar) {
                    Button(action: { }, label: {Text("ITEM2")})
                }
                ToolbarItem(placement: .bottomBar) {
                    Button(action: { }, label: {Text("ITEM3")})
                }
            }
        }
    }
}

The code below doesn't work for me:

init() {
    UIToolbar.appearance().barTintColor = UIColor.red
}

This code works:

init() {
  let coloredAppearance = UINavigationBarAppearance()
  coloredAppearance.configureWithOpaqueBackground()
  coloredAppearance.backgroundColor = .systemRed
  coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
  coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
  
  UINavigationBar.appearance().standardAppearance = coloredAppearance
  UINavigationBar.appearance().compactAppearance = coloredAppearance
  UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
  
  UINavigationBar.appearance().tintColor = .white
}

Taken from Kristaps Grinbergs' blog.

iOS 16 Onwards

enter image description here

Note: use .toolbarBackground(.visible, for: .navigationBar) The preferred visibility of the background of the bar.

Detail tutorial here - https://janeshswift.com/ios/swiftui/how-to-change-navigationview-colour-in-swiftui/

struct ContentView : View {
    var body: some View {
        NavigationStack {
            Text("Dashboard")
                .toolbar {
                    ToolbarItem(placement: .principal) {
                        Text("Cool Title")
                            .foregroundColor(.black)
                    }
                }
                .navigationBarTitleDisplayMode(.inline)
                .toolbarBackground(.red, for: .navigationBar)
                .toolbarBackground(.visible, for: .navigationBar)
        }
    }
}
Related