iOS中關於NavigationController中preferredStatusBarStyle一直不執行的問題

-、第一種做法(iOS9.0中已經廢除,建議使用)

iOS 7中,我們也可以使用UIApplication的statusBarStyle方法來設置狀態欄,過,首先需要停止使用View controller-based status bar appearance。project target的Info tab中,插入一個新的key,名字爲View controller-based status bar appearance,並將其值設置爲NO。

2782212-97482799424dc542.jpg

 

  需要改變狀態欄顏色的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.visibleViewControllerpreferredStatusBarStyle,那麼,我們寫UIViewcontroller裏面的方法就會被調用了,就能更改StatusBar的前景顏色了。
  真的能改嗎?跑起來毛用沒有。還要plist文件裏把View controller-based status bar appearance設置成YES。
總結:
  只要UIViewController重寫的childViewControllerForStatusBarStyle返回值是nil,那麼UIViewcontroller的preferredStatusBarStyle方法會被系統的Container(NavigationController或者UITabBarController)調用,而是調用childViewControllerForStatusBarStyle返回的UIViewController的preferredStatusBarStyle來控制StatuBar的顏色

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章