How to change PreferredStatusBarStyle programmatically

11.6k Views Asked by At

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.

3

There are 3 best solutions below

4
On

what you need to do, is to call the -setStatusBarStyle:animated: method thru the shared application, like this

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];

you can use it without the animated parameter as well. keep in mind that UIStatusBarStyleBlackOpaque is deprecated in iOS 7, documentation says you wanna use UIStatusBarStyleLightContent instead

edit: sorry, if u wanna use preferredStatusBarStyle, take a look at this preferredStatusBarStyle isn't called

2
On

On Swift 4:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

Hope it helps anybody else to find this post.

0
On

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()