知识准备
Apple提供了如下两个系统API用以修改StatusBar的样式:
- [UIApplication sharedApplication].statusBarStyle
- -(UIStatusBarStyle)preferredStatusBarStyle;
但是两者的使用是有条件的:需要在info.plist中,对View controller-based status bar appearance(Boolean - iOS)进行配置。
YES,[UIApplication sharedApplication].statusBarStyle 无效;
NO,preferredStatusBarStyle无效。
关于UIViewControllerBasedStatusBarAppearance,官方文档解释如下
UIViewControllerBasedStatusBarAppearance (Boolean - iOS) Specifies whether the status bar appearance is based on the style preferred by the view controller that is currently under the status bar. When this key is not present or its value is set to YES, the view controller determines the status bar style. When the key is set to NO, view controllers (or the app) must each set the status bar style explicitly using the UIApplication object.
UIViewControllerBasedStatusBarAppearance指定了status bar的样式是否由当前控制器决定。
方法一
- 在info.plist中,将View controller-based status bar appearance设为NO
- 在app delegate中:
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
- 在个别状态栏字体颜色不一样的vc中
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
方法二
- View controller-based status bar appearance默认值为YES
- 在vc中重写vc的preferredStatusBarStyle方法。
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleDefault;
}
- 如果没效果,可以在viewDidload中调用
// This should be called whenever the return values for the view controller's status bar attributes have changed.
[self setNeedsStatusBarAppearanceUpdate];
但是,当vc在nav中时,vc中的preferredStatusBarStyle方法根本不用被调用。原因是navigation controller中的preferredStatusBarStyle方法会对消息进行拦截。
解决办法有两个:
一、在vc中设置设置navbar的barStyle 属性,会影响status bar 的字体和背景色。但是这样会改变navigationbar的样式,所以不推荐。
二、自定义一个navigation controller的子类,在这个子类中对preferredStatusBarStyle消息进行分发:
- (UIStatusBarStyle)preferredStatusBarStyle{
UIViewController* topVC = self.topViewController;
return [topVC preferredStatusBarStyle];
}