iOS StatusBar 设置#
背景#
最近遇到设置 StatusBar 的问题,在 NavigationController 出来的界面设置 StatusBar 后一直不生效,印象中遇到过此类的问题,但是没有记录总结,还是花费了一点时间来找到原因,所以赶紧记录一下。
全局设置#
StatusBar 的全局设置,需要首先在info.plist
中设置View controller-based status bar appearance
为 NO,关掉按界面设置 status bar 显示。
显示 / 隐藏#
方法一:在 Target 下的 Deployment Info 中不勾选 / 勾选Hide status bar
方法二:代码设置
[UIApplication sharedApplication].statusBarHidden = YES;
设置#
方法一:在 Target 下的 Deployment Info 中设置Status Bar Style
方法二:代码设置
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
界面单独设置#
首先在info.plist
中设置View controller-based status bar appearance
为 YES,打开按界面设置 status bar 显示。
普通的 ViewController 设置:
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleDefault;
}
如果是 UINavigaitonController,则需要添加一个继承自 UINavigationController 的子类,在子类中设置如下代码,使用子类来控制。或者添加 UINavigaitonController 的 Category,在 Category 中设置如下代码
原因是:UIViewController 嵌套在 UINavigaitonController 中时,会优先调用 UINavigationController 的preferredStatusBarStyle
,所以直接在 UIViewController 中设置是不生效的。
- (UIStatusBarStyle)preferredStatusBarStyle {
return [self.topViewController preferredStatusBarStyle];
}
- (UIViewController *)childViewControllerForStatusBarStyle {
return self.topViewController;
}
问题#
modal 出来的 viewController 设置了 prefersStatusBarHidden 不生效的问题,需要设置 modalPresentationCapturesStatusBarAppearance 为 YES;
@implementation TargetViewController
- (instancetype)init {
self = [super init];
if (self) {
self.modalPresentationStyle = UIModalPresentationOverFullScreen;
self.modalPresentationCapturesStatusBarAppearance = YES;
}
return self;
}
- (BOOL)prefersStatusBarHidden {
return YES;
}