-、第一種做法(iOS9.0中已經廢除,不建議使用)
在iOS 7中,我們也可以使用UIApplication的statusBarStyle方法來設置狀態欄,不過,首先需要停止使用View controller-based status bar appearance。在project target的Info tab中,插入一個新的key,名字爲View controller-based status bar appearance,並將其值設置爲NO。
在需要改變狀態欄顏色的ViewController中在ViewDidLoad方法中增加:
[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
如果需要在全部View中都變色,可以寫在父類的相關方法中,或者寫到AppDelegate中。
二、介紹第二種做法,這個推薦
- (UIStatusBarStyle)preferredStatusBarStyle
在需要的控制器裏面重寫這個方法,返回值就是UIStatusBarStyleDefault或者UIStatusBarStyleLightContent在該方法裏面,如果只是簡單的返回值而已,那麼該界面在顯示的時候會立馬改變StatusBar的前景部分
如果該VC已經顯示出來了,你需要做的就是根據滾動的偏移量在實時更改StatusBar的前景顏色,那麼你就要用到[self setNeedsStatusBarAppearanceUpdate];
來顯視調用preferredStatusBarStyle這個方法才能更改StatusBar的顏色然而毛用,根本不會調用
要重寫(創建UINavigationController一個Category,在分類裏重寫)
- (UIViewController *)childViewControllerForStatusBarStyle:
這個方法默認返回值是nil。也就是當我們調用setNeedsStatusBarAppearanceUpdate的時候,系統會調用container(容器控制器)的preferredStatusBarStyle這個方法(app.window.rootViewController的preferred的方法,一般我們用UINavigationController或者UITabBarController來做container),也就是根本不會調用子控制器(我們所看到的UIViewcontroller)的preferredStatusBarStyle方法。這個時候- (UIViewController *)childViewControllerForStatusBarStyle:
就派上用場了。
給UINavigationController寫一個Catogory,implementation如下,然後記得在需要的界面包含頭文件就行
#import "UINavigationController+OLStatusBarStyle.h"
@implementation UINavigationController (OLStatusBarStyle)
- (UIViewController *)childViewControllerForStatusBarStyle{
return self.visibleViewController;
}
- (UIViewController *)childViewControllerForStatusBarHidden{
return self.visibleViewController;
}
該類擴展的意思就是,我重寫了,你不要調用Container(NavigationController或者UITabBarController)的preferredStatusBarStyle這個方法了,去調用self.visibleViewController
的preferredStatusBarStyle
,那麼,我們寫在UIViewcontroller裏面的方法就會被調用了,就能更改StatusBar的前景顏色了。
真的能改嗎?跑起來毛用沒有。還要在plist文件裏把View controller-based status bar appearance
設置成YES。
總結:
只要UIViewController重寫的childViewControllerForStatusBarStyle
返回值不是nil,那麼UIViewcontroller的preferredStatusBarStyle方法不會被系統的Container(NavigationController或者UITabBarController)調用,而是調用childViewControllerForStatusBarStyle
返回的UIViewController的preferredStatusBarStyle來控制StatuBar的顏色