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)
}
}
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)
}
}
}
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 {
,,,
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.