首页 > 解决方案 > 如何更改 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)
        }
    }
}

标签: iosswiftswiftui

解决方案


问题在于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 {
        ,,,
    }
}

推荐阅读