在iOS 9以后设置状态栏颜色不建议使用UIApplication来改变了,警告⚠️不能忍
- (void)setStatusBarStyle:(UIStatusBarStyle)statusBarStyle animated:(BOOL)animated NS_DEPRECATED_IOS(2_0, 9_0, "Use -[UIViewController preferredStatusBarStyle]")
1.在导航控制器里面实现下面方法:
//一般在BaseNavigationController里面实现
/**
设置显示栈顶控制器的状态栏颜色
*/
- (UIViewController *)childViewControllerForStatusBarStyle {
return self.topViewController;
}
2.在子控制器里面实现
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
这样系统push到某个控制器的时候就会显示此控制器preferredStatusBarStyle
方法返回状态栏style,不写默认显示黑色字体的状态栏
如何动态的改变状态栏颜色?
项目中有业务需求需要动态的改变状态栏颜色,StatusBarStyle可能在两种状态之间替换,最简单的是拿全局变量控制,但是为了以后调用方便,就写个分类,使用runtime 动态替换方法,当做一个小练习吧,以后用着也方便
贴一下代码:
// UIViewController+ForcedChangeStatusBarColor.h
#import <UIKit/UIKit.h>
@interface UIViewController (ForcedChangeStatusBarColor)
/**
@brief 控制器强制替换StatusBarStyle
*/
- (void)forcedChangeStatusBarStyle:(UIStatusBarStyle)style;
/**
@brief 执行过forcedChangeStatusBarStyle:方法的,使用此方法恢复到原先样式
*/
- (void)recoverStatusBarStyle;
@end
// UIViewController+ForcedChangeStatusBarColor.m
#import "UIViewController+ForcedChangeStatusBarColor.h"
#import <objc/runtime.h>
IMP originalIMP = NULL;
@implementation UIViewController (ForcedChangeStatusBarColor)
- (void)forcedChangeStatusBarStyle:(UIStatusBarStyle)style {
//保留原本方法
if (originalIMP == NULL) {
originalIMP = class_getMethodImplementation([self class], @selector(preferredStatusBarStyle));
}
//替换方法
IMP imp = style == UIStatusBarStyleLightContent ? (IMP)forcedChangeStatusBarStyleLightContent : (IMP)forcedChangeStatusBarStyleDefault;
class_replaceMethod([self class], @selector(preferredStatusBarStyle), imp, "i@:");
[self setNeedsStatusBarAppearanceUpdate];
}
- (void)recoverStatusBarStyle {
class_replaceMethod([self class], @selector(preferredStatusBarStyle), originalIMP, "i@:");
[self setNeedsStatusBarAppearanceUpdate];
}
UIStatusBarStyle forcedChangeStatusBarStyleDefault(id sender, SEL cmd) {
return UIStatusBarStyleDefault;
}
UIStatusBarStyle forcedChangeStatusBarStyleLightContent(id sender, SEL cmd) {
return UIStatusBarStyleLightContent;
}
@end