知識準備
Apple提供了如下兩個系統(tǒng)API用以修改StatusBar的樣式:
- [UIApplication sharedApplication].statusBarStyle
- -(UIStatusBarStyle)preferredStatusBarStyle片吊;
但是兩者的使用是有條件的:需要在info.plist中黔帕,對View controller-based status bar appearance(Boolean - iOS)進行配置瞬场。
YES隙咸,[UIApplication sharedApplication].statusBarStyle 無效;
NO虾宇,preferredStatusBarStyle無效旨剥。
關(guān)于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的樣式是否由當(dāng)前控制器決定臭墨。
方法一
- 在info.plist中哮翘,將View controller-based status bar appearance設(shè)為NO
- 在app delegate中:
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
- 在個別狀態(tài)欄字體顏色不一樣的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中調(diào)用
// This should be called whenever the return values for the view controller's status bar attributes have changed.
[self setNeedsStatusBarAppearanceUpdate];
但是令花,當(dāng)vc在nav中時署驻,vc中的preferredStatusBarStyle方法根本不用被調(diào)用泣洞。原因是navigation controller中的preferredStatusBarStyle方法會對消息進行攔截席舍。
解決辦法有兩個:
一勒魔、在vc中設(shè)置設(shè)置navbar的barStyle 屬性,會影響status bar 的字體和背景色践图。但是這樣會改變navigationbar的樣式掺冠,所以不推薦。
二码党、自定義一個navigation controller的子類德崭,在這個子類中對preferredStatusBarStyle消息進行分發(fā):
- (UIStatusBarStyle)preferredStatusBarStyle{
UIViewController* topVC = self.topViewController;
return [topVC preferredStatusBarStyle];
}