我想更改导航栏的背景颜色。但我做错了什么,颜色看起来如此不同?
我的代码:
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)
}
}
编辑:
与this solution ,情况有所好转,但颜色仍然存在差异。
我现在的代码:
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)
}
}
}
最佳答案
iOS 16
您可以使用以下修饰符直接在工具栏项目(例如导航栏)上设置任何颜色:
.toolbarBackground(.red, in: .navigationBar)
iOS 15 及更低版本
问题出在 UINavigationBar
的 backgroundImage
上。您应该将其设置为空的 UIImage,例如:
struct ContentView: View {
init() {
UINavigationBar.appearance().backgroundColor = .red // Or any other color
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
}
var body: some View {
,,,
}
}
关于ios - 如何更改 SwiftUI 中导航栏的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58822270/