SwiftUI Navigation Bar and Status Bar - Make them same color

The following works for me:

create an extension for UINavigationController which will change the following:

  • navigationbar background color
  • statusbar background color
  • navigationbar title color

    import UIKit
    
    extension UINavigationController {
        override open func viewDidLoad() {
            super.viewDidLoad()
    
            let appearance = UINavigationBarAppearance()
            //background color of the navigation and status bar
            appearance.backgroundColor = .black
            //color when the title is large
            appearance.largeTitleTextAttributes.updateValue(UIColor.white, forKey: NSAttributedString.Key.foregroundColor)
            //color when the title is small
            appearance.titleTextAttributes.updateValue(UIColor.white, forKey: NSAttributedString.Key.foregroundColor)
    
            // change the background- and title foregroundcolor for navigationbar
            navigationBar.standardAppearance = appearance
            navigationBar.scrollEdgeAppearance = appearance
            navigationBar.compactAppearance = appearance
            // change color of navigationbar items
            navigationBar.tintColor = UIColor.white
        }
    }
    

however this will not change the statusbar foreground color. for that we need to do the following:

import SwiftUI

class HostingController<Content> : UIHostingController<Content> where Content : View {
    @objc override dynamic open var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

and then in our scenedelegate

we need to replace

window.rootViewController = UIHostingController(rootView: contentView)

with

window.rootViewController = HostingController(rootView: contentView)

When I started coding with SwiftUI, I faced the same issue and after so much research I found the solution.

Put the below code in the SceneDelegate class.

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {        
    let newAppearance = UINavigationBarAppearance()
    newAppearance.configureWithOpaqueBackground()
    newAppearance.backgroundColor = .black
    newAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]

    UINavigationBar.appearance().standardAppearance = newAppearance

    //Other code for displaying the first screen
}

UINavigationBarAppearance class is used for changing appearance of the navigation bar and it is available from iOS 13.

The above code will change the navigation bar style of all the controllers.