Search code examples
iosswiftstatusbar

setStatusBarStyle:animated: deprecated


I'm currently developing an app (in Swift 3) on Xcode 8 beta, for iOS 10.

What I want to achieve is to change status bar style within a view controller at run time, for changing the theme from daytime theme to night theme. I've found out that the method I used to use when I was developing another app in the past was deprecated, as shown here on the API reference.

However, preferredStatusBarStyle won't work here since I would like to change it within a single view controller.

Can anybody think of other ways to perform this?

Thanks in advance

EDIT:

To be clear, what I want to do is to change the style when the view controller is already on screen.


Solution

  • You can create a statusBarStyle variable that when changed updates the status bar appearance. If you only want this to affect one controller, simply reverse the effect when the Controller will or did disappear.

    var statusBarStyle: UIStatusBarStyle = .lightContent {
        didSet {
            setNeedsStatusBarAppearanceUpdate()
        }
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return statusBarStyle
    }
    

    The above solution will override the previous controller's status bar style before the controller appears. If you want to change the status bar style when the controller appears, try this:

    var statusBarStyle: UIStatusBarStyle? {
        didSet {
            setNeedsStatusBarAppearanceUpdate()
        }
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return statusBarStyle ?? super.preferredStatusBarStyle
    }
    
    override func viewDidAppear(animated: Bool) {
    
        super.viewDidAppear(animated)
    
        statusBarStyle = .lightContent
    }