Reputation: 699
I would like to change the background color of the navigation bar. But what am I doing wrong that the colors look so different?
My code:
UINavigationBar.appearance().backgroundColor = .red
return VStack(spacing: 0) {
Text("Test")
.padding(.top, 9.5)
.padding(.bottom, 8)
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.red)
.font(.footnote)
NavigationView {
Text("Hello")
.navigationBarTitle(Text("Hi"), displayMode: .inline)
}
}
EDIT:
With this solution, it gets better but there is still a difference in color.
My code now:
struct ContentView: View {
var body: some View {
VStack(spacing: 0) {
Text("Test")
.padding(.top, 9.5)
.padding(.bottom, 8)
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color("red")) // Now I use a color set
.font(.footnote)
NavigationView {
Text("Hello")
.navigationBarTitle(Text("Hi"), displayMode: .inline)
.background(NavigationConfigurator { nc in
nc.navigationBar.barTintColor = UIColor(named: "red") // Now I use a color set
})
}
}
}
}
struct NavigationConfigurator: UIViewControllerRepresentable {
var configure: (UINavigationController) -> Void = { _ in }
func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfigurator>) -> UIViewController {
UIViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfigurator>) {
if let nc = uiViewController.navigationController {
self.configure(nc)
}
}
}
Upvotes: 2
Views: 4410
Reputation: 119128
You can set any color directly on toolbar items like the navigation bar with the following modifier:
.toolbarBackground(.red, in: .navigationBar)
The issue is with the UINavigationBar
's backgroundImage
. You should set it to an empty UIImage
like:
struct ContentView: View {
init() {
UINavigationBar.appearance().backgroundColor = .red // Or any other color
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
}
var body: some View {
,,,
}
}
Upvotes: 4
Reputation: 9463
When you specify the displayMode: .inline
parameter, the color underneath the navigation bar (in this case, white) gets blended into the nav bar's color, leaving you with this pinkish color. You will get full red if its a large title style.
This answer is a better way of setting the navigation bar color, and will work even with the .inline
style.
Finally, note that Color.red
is actually the same as UIColor.systemRed
. If you use UIColor.red
, you'll notice a difference in Dark Mode.
Upvotes: 1