首页 > 解决方案 > SwiftUI - 导航栏颜色更改未应用于状态栏

问题描述

我有以下内容:

var body: some View {
        NavigationView {
            VStack {
                 Text("Hello")
            }.navigationBarTitle("Edit Profile", displayMode: .inline)
             .background(NavigationConfiguration { nc in
                 nc.navigationBar.barTintColor = .red
                 nc.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black]
            })
        }.navigationViewStyle(StackNavigationViewStyle())
}

对于导航栏的配置,我有:

struct NavigationConfiguration: UIViewControllerRepresentable {
    var configuration: (UINavigationController) -> Void = { _ in }
    func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfiguration>) -> UIViewController {
        UIViewController()
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfiguration>) {
        if let nc = uiViewController.navigationController {
            self.configuration(nc)
        }
    }
}

但由于某种原因,顶部状态栏被忽略了,颜色也没有应用到它:

状态栏图片

红色如何也应用于导航栏上方的状态栏,我希望它是相同的颜色。

我尝试了以下方法,但失败了:

init() {
    UINavigationBar.appearance().backgroundColor = .red
}

标签: swiftuinavigationcontrollerswiftuiuinavigationbarswiftui-navigationlink

解决方案


尝试以下操作(它应该可以工作,至少在 Xcode 11.4 / iOS 13.4 中测试过,但有人报告它不是,所以它可能是依赖的)

演示

init() {
       let navBarAppearance = UINavigationBarAppearance()
       navBarAppearance.configureWithOpaqueBackground()
       navBarAppearance.backgroundColor = UIColor.systemRed

       UINavigationBar.appearance().standardAppearance = navBarAppearance
}

推荐阅读