Ios 如何更改SwiftUI中导航栏的背景色?
我想更改导航栏的背景色。但是我做错了什么,颜色看起来如此不同 我的代码:Ios 如何更改SwiftUI中导航栏的背景色?,ios,swift,swiftui,Ios,Swift,Swiftui,我想更改导航栏的背景色。但是我做错了什么,颜色看起来如此不同 我的代码: UINavigationBar.appearance().backgroundColor = .red return VStack(spacing: 0) { Text("Test") .padding(.top, 9.5) .padding(.bottom, 8) .frame(minWidth: 0, maxWidth: .infinity)
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)
}
}
}
struct ContentView:View{
var body:一些观点{
VStack(间距:0){
文本(“测试”)
.填充(.top,9.5)
.padding(.bottom,8)
.frame(最小宽度:0,最大宽度:无穷大)
.background(颜色(“红色”)//现在我使用颜色集
.font(.footnote)
导航视图{
文本(“你好”)
.navigationBarTitle(文本(“Hi”),显示模式:。内联)
.background(导航配置程序{nc in
nc.navigationBar.barTintColor=UIColor(名为:“red”)//现在我使用一个颜色集
})
}
}
}
}
结构导航配置器:UIViewControllerRepresentable{
变量配置:(UINavigationController)->Void={uuin}
func makeUIViewController(上下文:UIViewControllerRepresentableContext)->UIViewController{
UIViewController()
}
func updateUIViewController(uViewController:uiViewController,上下文:UIViewControllerRepresentableContext){
如果让nc=uiViewController.navigationController{
自配置(nc)
}
}
}
当您指定显示模式:.inline
参数时,导航栏下方的颜色(在本例中为白色)将混合到导航栏的颜色中,留下粉红色。如果它是一个大标题样式,您将得到全红
是设置导航栏颜色的更好方法,即使使用.inline
样式也可以
最后,请注意
Color.red
实际上与UIColor.systemRed
相同。如果使用UIColor.red
,您会注意到在暗模式下的差异。问题在于UINavigationBar
的背景图像。您应该将其设置为空的UIImage
,如:
struct ContentView: View {
init() {
UINavigationBar.appearance().backgroundColor = .red // Or any other color
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
}
var body: some View {
,,,
}
}
也许这是有帮助的:另外,您同时使用了背景(颜色(“红色”)
和UIColor(名称:“红色”)
。我认为这没有什么区别,因为我使用了相同的答案,谢谢。不幸的是,这对我来说并不奏效,但也许我误解了什么。我还为问题添加了一个屏幕截图,以显示此解决方案的变化。