在 iOS 7 中,隱藏狀態列(status bar)的行為發生了變化,關鍵在於 info.plist 中的一項設定:View controller-based status bar appearance。
當該項設為 YES 時,View controller 對狀態列的設定優先級高於 application;設為 NO 時則以 application 的設定為準,此時 view controller 的 prefersStatusBarHidden 方法根本不會被呼叫。
此時 view controller 的設定優先級更高,用以下方式隱藏狀態列:
1、在 view controller 中呼叫 setNeedsStatusBarAppearanceUpdate 更新狀態列顯示:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
[self prefersStatusBarHidden];
[self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
}
}
2、覆寫 prefersStatusBarHidden 並回傳 YES:
- (BOOL)prefersStatusBarHidden {
return YES;
}
此時 application 的設定優先級最高,直接呼叫:
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];
若需同時支持 iOS 6 與 iOS 7,處理方式如下:
一、若 View controller-based status bar appearance 設為 NO,則在 iOS 6 與 iOS 7 中都可用同一方法隱藏:
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];
二、若設為 YES,則需判斷系統版本:iOS 6 仍透過 sharedApplication 隱藏;iOS 7 則用 setNeedsStatusBarAppearanceUpdate 搭配 prefersStatusBarHidden 來隱藏。
讀取 info.plist 中該設定的程式碼如下:
NSNumber *isVCBasedStatusBarAppearanceNum = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"];
if (isVCBasedStatusBarAppearanceNum) {
_isVCBasedStatusBarAppearance = isVCBasedStatusBarAppearanceNum.boolValue;
} else {
_isVCBasedStatusBarAppearance = YES; // 預設值
}