How to change PreferredStatusBarStyle programmatically

ikanimo picture ikanimo · Dec 12, 2013 · Viewed 10k times · Source

I'd like to change the color of status bar from white to black by press button, programmatically only in a single-ViewController

This is the code:

- (UIStatusBarStyle)preferredStatusBarStyle {
    NSLog(@"PreferredStatusBarStyle");
    if(nav_bar.alpha==1)
    {
        NSLog(@"->UIStatusBarStyleBlackOpaque");
        return UIStatusBarStyleBlackOpaque;
    }
    else
    {
        NSLog(@"->UIStatusBarStyleLightContent");
        return UIStatusBarStyleLightContent;
    }}

then When I press a button action is:

[self setNeedsStatusBarAppearanceUpdate];

But this doesn't work!

When I press the button log write the correct status according to navbar.alpha, but statusbar text color remain UIStatusBarStyleBlackOpaque like when view appear.

Answer

rdougan picture rdougan · Oct 25, 2015

setStatusBarStyle:animated: has been deprecated. In iOS9 you can achieve the same thing using preferredStatusBarStyle and setNeedsStatusBarAppearanceUpdate.

In your View Controller:

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    if (condition) {
        return .LightContent
    }

    return .Default
}

And then when your condition changes:

self.setNeedsStatusBarAppearanceUpdate()