27

I'm writing an iOS App with multiple views. I've set the App to use ViewController-based status bar style, which allows me to use the following code

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
} 

That worked like expected.

But then I've embedded the views in a navigation controller and connected a BarButtonItem with a showSegue. Since then the ViewController of the view switched to ignores the style settings and shows the default black status bar.

Robin Daugherty
  • 7,115
  • 4
  • 45
  • 59
Kevin H. Klein
  • 403
  • 1
  • 5
  • 14

2 Answers2

79

When you're in a navigation controller that will not get called. The navigation controller's preferredStatusBarStyle will be called. Try this along with your code:

extension UINavigationController {

   open override var preferredStatusBarStyle: UIStatusBarStyle {
      return topViewController?.preferredStatusBarStyle ?? .default
   }
}
rmickeyd
  • 1,551
  • 11
  • 13
  • Guessed something like that. Got it working by implementing a custom NavigationController Class overriding that var. But your solution is better. Thanks a lot! – Kevin H. Klein Dec 07 '16 at 20:39
  • 1
    Great solution! Don't forget add to info.plist View controller-based status bar appearance = Yes – Codenator81 May 28 '18 at 11:43
  • 1
    The proper way to do it is overriding `childForStatusBarStyle` instead. – Rivera Apr 09 '19 at 14:30
  • 1
    @Codenator81 for Xcode 10+, Swift 4.2 it's YES by default – mojtaba al moussawi Apr 16 '19 at 09:06
  • 1
    The compiler is allowing you to override the extension for compatibility with Objective-C. But it's actually violating the language directive. https://stackoverflow.com/a/38274660/1442541 – evya Nov 12 '20 at 05:07
  • am i put the code on viewcontroller? or create new file for the extension? because it's not going there in my viewcontroller (debugging) – lauwis Oct 19 '22 at 12:11
11

There is a solution that is a bit more concise (and recommended by Apple):

extension UINavigationController {
    override open var childForStatusBarStyle: UIViewController? {
        return topViewController
    }
}
joern
  • 27,354
  • 7
  • 90
  • 105