iOS中关于NavigationController中UIStatusBar更改为白色,最新方法:preferredStatusBarStyle
之前配置状态栏的前景色比较简单,方法如下:
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
上面这个方法已经被iOS 9给废掉了,所以现在推荐用下面的方法来配置:
第一步:配置Info.list下图中的属性:
第二步:在需要配置的UIViewController控制器里重写下面的方法:
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContentj;
}
第三步:用如下方法,来调用preferredStatusBarStyle这个方法
[self setNeedsStatusBarAppearanceUpdate];
配置到这里,你以为就结束了,你太天真了,还需要去重写一下UINavigtionController的方法,可以用扩展重写
第四步:给UINavigationController写一个扩展,记得在调用的地方,添加头文件:
#import "UINavigationController+StatusBarStyle"
@implementation UINavigationController (StatusBarStyle)
-(UIViewController *)childViewControllerForStatusBarStyle{
return self.visibleViewController;
}
-(UIViewController *)childViewControllerForStatusBarHidden{
return self.visibleViewController;
}
为什么要重写这个方法了-(UIViewController *)childViewControllerForStatusBarStyle ?
这个方法,默认返回值是nil。也就是当我们调用setNeedsStatusBarAppearanceUpdate的时候,系统会调用container(容器控制器)的preferredStatusBarStyle这个方法(app.window.rootViewController的preferred的方法,一般我们用UINavigationController或者UITabBarController来做container),也就是根本不会调用子控制器(我们所看到的UIViewcontroller)的preferredStatusBarStyle方法。这个时候- (UIViewController *)childViewControllerForStatusBarStyle:就派上用场了
至此,总算大功告成!