To change a navigation bar color in SwiftUI in iOS we need to apply the toolbarBackground modifier to the content view of NavigationStack.
toolbarBackground accepts 2 parameters:
ShapeStyle: The style to display as the bar background.
ToolbarPlacement: The bars to place the style in. We want to change the navigation bar color, so we will set this to .navigationBar
In this Xcode example we will set the bar background color to blue:
struct ContentView: View {
var body: some View {
NavigationStack {
List {
Text("Hello, SwiftUI!")
}
.navigationTitle("Navigation Title")
.toolbarBackground(
// 1
.blue,
// 2
for: .navigationBar)
}
}
}
1) We set the color to blue.
2) We set .navigationBar for ToolbarPlacement to apply background color to navigation bar.
Once we move the content up the navigation bar becomes visible and the color is blue.
Background visibility
To control background visibility we use a variation of .toolbarBackground modifier which accepts Visibility instead of ShapeStyle
Take a look at this example:
struct ContentView: View {
var body: some View {
NavigationStack {
List {
Text("Hello, SwiftUI!")
}
.navigationTitle("Navigation Title")
.toolbarBackground(
.blue,
for: .navigationBar)
.toolbarBackground(.visible, for: .navigationBar)
}
}
}
Leave a Reply