在iOS 9以后設(shè)置狀態(tài)欄顏色不建議使用UIApplication來(lái)改變了,警告??不能忍
- (void)setStatusBarStyle:(UIStatusBarStyle)statusBarStyle animated:(BOOL)animated NS_DEPRECATED_IOS(2_0, 9_0, "Use -[UIViewController preferredStatusBarStyle]")
1.在導(dǎo)航控制器里面實(shí)現(xiàn)下面方法:
//一般在BaseNavigationController里面實(shí)現(xiàn)
/**
設(shè)置顯示棧頂控制器的狀態(tài)欄顏色
*/
- (UIViewController *)childViewControllerForStatusBarStyle {
return self.topViewController;
}
2.在子控制器里面實(shí)現(xiàn)
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
這樣系統(tǒng)push到某個(gè)控制器的時(shí)候就會(huì)顯示此控制器preferredStatusBarStyle
方法返回狀態(tài)欄style专挪,不寫(xiě)默認(rèn)顯示黑色字體的狀態(tài)欄
如何動(dòng)態(tài)的改變狀態(tài)欄顏色?
項(xiàng)目中有業(yè)務(wù)需求需要?jiǎng)討B(tài)的改變狀態(tài)欄顏色片排,StatusBarStyle可能在兩種狀態(tài)之間替換寨腔,最簡(jiǎn)單的是拿全局變量控制,但是為了以后調(diào)用方便率寡,就寫(xiě)個(gè)分類(lèi)迫卢,使用runtime 動(dòng)態(tài)替換方法,當(dāng)做一個(gè)小練習(xí)吧冶共,以后用著也方便
貼一下代碼:
// UIViewController+ForcedChangeStatusBarColor.h
#import <UIKit/UIKit.h>
@interface UIViewController (ForcedChangeStatusBarColor)
/**
@brief 控制器強(qiáng)制替換StatusBarStyle
*/
- (void)forcedChangeStatusBarStyle:(UIStatusBarStyle)style;
/**
@brief 執(zhí)行過(guò)forcedChangeStatusBarStyle:方法的靖避,使用此方法恢復(fù)到原先樣式
*/
- (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