title: iOS StatusBar Settings
tags:
- Technology
- iOS
date: 2021-06-30 15:36#
iOS StatusBar Settings#
Background#
Recently, I encountered an issue with setting the StatusBar in iOS. The StatusBar setting did not take effect on the screen that appeared from the NavigationController. 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 quickly.
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-screen status bar appearance.
Show/Hide#
Method 1: In the Deployment Info section under Target, uncheck/check Hide status bar
.
Method 2: Code setting
[UIApplication sharedApplication].statusBarHidden = YES;
Style Setting#
Method 1: In the Deployment Info section under Target, set Status Bar Style
.
Method 2: Code setting
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
Individual Screen Settings#
First, set View controller-based status bar appearance
to YES in info.plist
to enable per-screen status bar appearance.
For a regular ViewController:
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleDefault;
}
If it is a UINavigationController, you need to add a subclass of UINavigationController and set the following code in the subclass. Alternatively, you can add a Category for UINavigationController and set the following code in the Category.
The reason is that when a UIViewController is nested in a UINavigationController, the preferredStatusBarStyle
of UINavigationController will be called first. Therefore, directly setting it in UIViewController will not take effect.
- (UIStatusBarStyle)preferredStatusBarStyle {
return [self.topViewController preferredStatusBarStyle];
}
- (UIViewController *)childViewControllerForStatusBarStyle {
return self.topViewController;
}
Issue#
The issue of prefersStatusBarHidden not taking effect on a modal viewController 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;
}