Search code examples
swiftuinavigationcontrollerswiftuiuinavigationbarswiftui-navigationlink

SwiftUI - Navigation bar colour change not being applied to status bar


I have the following:

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())
}

For the configuration of the nav bar i have:

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)
        }
    }
}

But for some reason the top status bar is being left out and the colour is not being applied to it:

Status bar image

How can the red colour also be applied to the status bar above the nav bar, I want it to be the same colour.

I've tried the below, but this fails:

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

Solution

  • Try the following (it should work, at least as tested with Xcode 11.4 / iOS 13.4, but someone reported it was not, so it might be dependent)

    demo

    init() {
           let navBarAppearance = UINavigationBarAppearance()
           navBarAppearance.configureWithOpaqueBackground()
           navBarAppearance.backgroundColor = UIColor.systemRed
    
           UINavigationBar.appearance().standardAppearance = navBarAppearance
    }