知識(shí)普及
蘋果各機(jī)型的狀態(tài)欄高度為固定的20個(gè)像素,狀態(tài)欄分為前景和背景兩部分:
- 前景就是狀態(tài)欄顯示的字體、運(yùn)營商、電量等內(nèi)容,
- 背景是前景后面顯示的純色部分。
我項(xiàng)目中需求:特定的UIViewController中顯示不同狀態(tài)欄的顏色,主要用到兩種狀態(tài):
-
前景色為白色,背景色為黑色
-
前景色為黑色,背景色為白色
改變前景
上面兩種狀態(tài)的前景分別對(duì)應(yīng)下面兩種類型
typedef NS_ENUM(NSInteger, UIStatusBarStyle) {
UIStatusBarStyleDefault = 0, //默認(rèn)模式,前景內(nèi)容為黑色,用在亮色背景上
UIStatusBarStyleLightContent = 1, //前景內(nèi)容為白色,用在暗色背景上
}
由于不同的頁面顯示類型不一樣,所以不能全局設(shè)置,我們需要在不同的UIViewController中設(shè)置對(duì)應(yīng)的顏色,首先說一下思路,在viewWillAppear方法中設(shè)置當(dāng)前 UIViewController 的狀態(tài)欄顏色,在viewWillDisappear恢復(fù)默認(rèn)的狀態(tài)欄顏色,當(dāng)然這里并不是項(xiàng)目中的每個(gè)頁面都需要更改狀態(tài)欄顏色,我們會(huì)有一個(gè)默認(rèn)的狀態(tài)欄顏色。下面是具體步驟:
- 在info.plist中添加
View controller-based status bar appearance并設(shè)置為NO - 在UIViewController對(duì)應(yīng)方法中添加對(duì)應(yīng)內(nèi)容,如下
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//改變狀態(tài)欄字體和背景顏色
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:YES];
//恢復(fù)狀態(tài)欄字體和背景顏色
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}
當(dāng)然這里我們只改變了前景顏色,當(dāng)背景為黑色時(shí)我們將前景也改為UIStatusBarStyleDefault將什么都看不到。所以我們在更改時(shí),需要前景和背景一起改,繼續(xù)往下看。
改變背景
背景顏色的改變使用的是KVC方式,直接上代碼
//改變狀態(tài)欄背景顏色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
statusBar.backgroundColor = color;
}
}
setStatusBarBackgroundColor的參數(shù)color就是需要設(shè)置的顏色,所以上面UIViewController中對(duì)應(yīng)的方法改為
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//改變狀態(tài)欄字體和背景顏色
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];//前景
[self setStatusBarBackgroundColor:[UIColor blackColor]];//背景
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:YES];
//恢復(fù)狀態(tài)欄字體和背景顏色
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];//前景
[self setStatusBarBackgroundColor:[UIColor whiteColor]];//背景
}
這里只是根據(jù)需求簡單的設(shè)置了狀態(tài)欄的類型,沒有涉及狀態(tài)更多的內(nèi)容和原理。如有問題望多指教。

