ios - 如何更改 SwiftUI 中导航栏的背景颜色?
问题描述
我想更改导航栏的背景颜色。但是我做错了什么颜色看起来如此不同?
我的代码:
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)
}
}
编辑:
使用此解决方案,它会变得更好,但颜色仍然存在差异。
我现在的代码:
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)
}
}
}
解决方案
问题在于UINavigationBar
's backgroundImage
。您应该将其设置为空,UIImage
例如:
struct ContentView: View {
init() {
UINavigationBar.appearance().backgroundColor = .red // Or any other color
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
}
var body: some View {
,,,
}
}
推荐阅读
- python - Python Selenium如何找到输入按钮
- ruby-on-rails - 为 ruby 安装导轨时遇到问题
- java - 当 HttpServletRequest getHeader 返回未知?
- php - pg_dump 从一个 Cloud Foundry 实例到另一个
- swift - 如何在 Swift 4 中使用 sizeof() 方法
- haskell - 解析不明确的类型变量
- jquery-bootgrid - 如何应用引导网格过滤器?
- python - django project_form 无效?
- r - 如何将 scale 和 dist 与具有列名的数据集一起使用
- javascript - 如何将相同的元素添加到javascript数组n次