狀態欄(Status Bar)的樣式與顯示內容,可以透過 UIApplication 類別提供的方法來控制。本文整理常見操作,並示範如何打造一個自定義的狀態欄提示。
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; //顯示 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; //隱藏
狀態欄的這些改變只在你的程式內部生效,退出程式後就會復原。
UIApplication *myApp = [UIApplication sharedApplication];
1. 隱藏狀態欄:
[myApp setStatusBarHidden:YES animated:YES];
提醒:隱藏後可用區域會增加約 320×20 的大小,所以最好在建立任何 window 或 view 之前就先隱藏。
2. 狀態欄風格:
[myApp setStatusBarStyle: UIStatusBarStyleBlackOpaque];
typedef enum {
UIStatusBarStyleDefault,
UIStatusBarStyleBlackTranslucent,
UIStatusBarStyleBlackOpaque
} UIStatusBarStyle;
3. 狀態欄方向:
[myApp setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:NO];
typedef enum {
UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait, //豎屏
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown, //上下顛倒
UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight, //逆時針橫屏
UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft //順時針橫屏
} UIInterfaceOrientation;
有時需要在狀態欄顯示自定義訊息,例如告知使用者訊息正在發送、發送成功或失敗,如下圖:

先定義一個包含 Label 的自定義狀態欄類別:
@interface CustomStatusBar : UIWindow
{
UILabel *_messageLabel;
}
- (void)showStatusMessage:(NSString *)message;
- (void)hide;
@end
接著讓它的大小與系統狀態欄一致、背景設為黑色:
self.frame = [UIApplication sharedApplication].statusBarFrame; self.backgroundColor = [UIColor blackColor];
為了讓它能覆蓋系統狀態欄,還要調高 windowLevel。在 iOS 中,windowLevel 決定 UIWindow 的顯示層次,預設為 UIWindowLevelNormal(0.0),系統另定義了 UIWindowLevelAlert 與 UIWindowLevelStatusBar 等層次:
self.windowLevel = UIWindowLevelStatusBar + 1.0f;
最後為顯示與隱藏加上一點動畫:
- (void)showStatusMessage:(NSString *)message
{
self.hidden = NO;
self.alpha = 1.0f;
_messageLabel.text = @"";
CGSize totalSize = self.frame.size;
self.frame = (CGRect){ self.frame.origin, 0, totalSize.height };
[UIView animateWithDuration:0.5f animations:^{
self.frame = (CGRect){ self.frame.origin, totalSize };
} completion:^(BOOL finished){
_messageLabel.text = message;
}];
}
- (void)hide
{
self.alpha = 1.0f;
[UIView animateWithDuration:0.5f animations:^{
self.alpha = 0.0f;
} completion:^(BOOL finished){
_messageLabel.text = @"";
self.hidden = YES;
}];
}
透過在狀態欄顯示自定義訊息,就能給使用者友善又不影響操作的提示。