How to customize the background color of navigation bars, tab bars, and toolbars
How to customize the background color of navigation bars, tab bars, and toolbars 관련
Updated for Xcode 15
New in iOS 16
SwiftUI's toolbarBackground()
modifier lets us customize the way toolbars look in our app, controlling the styling of NavigationStack
, TabView
, and other toolbars as needed.
For example, this shows a list of 100 rows using a teal background color for the navigation bar:
NavigationStack {
List(0..<100) {
Text("Row \($0)")
}
.navigationTitle("100 Rows")
.toolbarBackground(.teal)
}
Important
The background you choose here is used when the system deems it necessary, rather than always. So, in the code above the navigation stack view will appear without the color at first, but will change color as soon as the list scrolls under the navigation bar.
Using toolbarBackground(.teal)
doesn't specify which toolbar should be colored teal, so it's down to the system to select whatever is the primary toolbar – that's the navigation bar on iOS, but on macOS it will be the window toolbar instead.
If you want one or two bar types to be colored, or perhaps if you want to provide different styling for each bar, you can provide a second parameter to toolbarBackground()
to get extra control. For example, we could ask the system to color both the tab bar and the navigation bar like this:
TabView {
NavigationStack {
List(0..<100) {
Text("Row \($0)")
}
.navigationTitle("100 Rows")
.toolbarBackground(.orange, for: .navigationBar, .tabBar)
}
.tabItem {
Label("Rows", systemImage: "list.bullet")
}
}
This modifier has one other important use: rather than specify a background color, you can ask the system to hide the background entirely, like this:
NavigationStack {
List(0..<100) {
Text("Row \($0)")
}
.navigationTitle("100 Rows")
.toolbarBackground(.hidden)
}
In that example, the list content will appear directly alongside the navigation title as the user scrolls. If you take this approach, please ensure your main content and toolbar content don't clash when they overlap!