Updated for Xcode 14.2
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)
}
Download this as an Xcode project
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")
}
}
Download this as an Xcode project
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)
}
Download this as an Xcode project
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!
SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Link copied to your pasteboard.