2

I am trying to change the UIStatusBar tint color in a specific UIViewController.

Here is my code:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    self.setNeedsStatusBarAppearanceUpdate()

}

Nothing is happening.

Rengers
  • 14,911
  • 1
  • 36
  • 54
Cal
  • 422
  • 6
  • 20
  • Possible duplicate of [preferredStatusBarStyle isn't called](https://stackoverflow.com/questions/19022210/preferredstatusbarstyle-isnt-called) – Nilanshu Jaiswal Nov 24 '18 at 11:11
  • @Damon, while I could agree that this *may* be a dup, that one has *much more* details than this one - including the specifics that we are talking a `UINavigationController` scenario. SO far, the OP has only said "in a specific VC". TO the OP, could you provide more specifics? I've successfully overriden `preferredStatusBarStyle` many time. It doesn't need a call to `setNeedsStatusBarAppearanceUpdate` under most circumstances (including setting things in *every* VC depending o how you set it the first time). If you copy/paste the posted code into a *new* project, does it work? –  Nov 24 '18 at 11:51

3 Answers3

1

On a UINavigationController, preferredStatusBarStyle is not called because its topViewController is preferred to self. So, to get preferredStatusBarStyle called on an UINavigationController, you need to change its childViewControllerForStatusBarStyle.

To do it for one UINavigationController:

class MyRootNavigationController: UINavigationController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    override var childViewControllerForStatusBarStyle: UIViewController? {
        return nil
    }
}
Ammar
  • 380
  • 6
  • 16
0

You can add an extension to UINavigationController:

extension UINavigationController {
    open override var childForStatusBarStyle: UIViewController? {
        return visibleViewController
    }
}

Then for view controllers that you want a light status bar (white time, icons etc.), then override preferredStatusBarStyle:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return UIStatusBarStyle.lightContent
}

For a dark status bar, you don't have to do anything.

Matt Le Fleur
  • 2,708
  • 29
  • 40
  • Where do I put this extension? – Cal Nov 25 '18 at 11:06
  • Anywhere you want :) You can put it below your entire view controller (not in the same class). If you want to be more organised and avoid a large file, you can put it in it's own file – Matt Le Fleur Nov 26 '18 at 12:15
0

You may need to add "View controller-based status bar appearance" with a value of "YES" in your info.plist