How to change status bar color?

Viewed 6132

In my app, I am using an image as the background for my ViewController's. For the status bar in the project settings I set: Status Bar Style - Default. I don't use anything else for the status bar.

The problem is when the iOS dark mode is enabled my status bar goes white. And I need it to stay black. How to fix it?

Also I don't want to turn off iOS dark/light mode supporting in the app. So the Appearance Light in the Info.plist doesn't quite work for me.

2 Answers

Set your status bar style to dark content:

enter image description here

After that add in your info.plist View controller-based status bar appearance and set it to NO

enter image description here

UPDATE

if you want dark content only in determinate controller add setNeedsStatusBarAppearanceUpdate in viewWillAppear and after that override preferredStatusBarStyle:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    setNeedsStatusBarAppearanceUpdate()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
    if #available(iOS 13.0, *) {
        return .darkContent
    } else {
        return .default
    }

Begin with navigation Controller:

In your Scene delegate declare your first navigation controller:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    window?.makeKeyAndVisible()
    let controller = UINavigationController(rootViewController: FirstViewController())
    controller.navigationBar.barStyle = .black
    window?.rootViewController = controller
}

in SecondViewController override the status bar style

override var preferredStatusBarStyle: UIStatusBarStyle {
    if #available(iOS 13.0, *) {
        return .darkContent
    } else {
        return .default
    }
}

For each ViewController you can set status bar color with simple override method.

override var preferredStatusBarStyle: UIStatusBarStyle {
    if #available(iOS 13, *) {
        return .darkContent
    } else {
        return .default
    }
}

Don't forget to set View controller-based status bar appearance to YES in your Info.plist.

Related