今是昨非

今是昨非

日出江花红胜火,春来江水绿如蓝

iOS StatusBar Settings

iOS StatusBar Settings#

Background#

Recently, I encountered an issue with setting the StatusBar in iOS. The StatusBar setting in the view presented by the NavigationController was not taking effect. I vaguely remember encountering similar issues before, but I didn't document or summarize them. So, I spent some time finding the reason and decided to record it.

Global Settings#

To globally set the StatusBar, you need to first set View controller-based status bar appearance to NO in info.plist to disable per-interface status bar appearance.

Show/Hide#

Method 1: In the Target's Deployment Info, uncheck/check Hide status bar

wecom20210630-151212@2x.png

Method 2: Code setting

[UIApplication sharedApplication].statusBarHidden = YES;

Style#

Method 1: In the Target's Deployment Info, set Status Bar Style

wecom20210630-151212@2x.png

Method 2: Code setting

[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;

Individual Interface Settings#

First, set View controller-based status bar appearance to YES in info.plist to enable per-interface status bar appearance.

For a regular ViewController:

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

If it's a UINavigationController, you need to add a subclass of UINavigationController and set the following code in the subclass. Alternatively, you can add a category to UINavigationController and set the following code in the category.

The reason is that when a UIViewController is nested in a UINavigationController, the preferredStatusBarStyle of the UINavigationController will be called first. So, setting it directly in the UIViewController won't take effect.


- (UIStatusBarStyle)preferredStatusBarStyle {
    return [self.topViewController preferredStatusBarStyle];
}

- (UIViewController *)childViewControllerForStatusBarStyle {
    return self.topViewController;
}

Issue#

The issue of prefersStatusBarHidden not taking effect for a modal view controller can be resolved by setting modalPresentationCapturesStatusBarAppearance to YES.

@implementation TargetViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
        self.modalPresentationCapturesStatusBarAppearance = YES;
    }
    return self;
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

Reference#

iOS Development - Summary of Status Bar Settings

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.