狀態列(Status Bar)雖然只有 20 點高,卻是使用者感知 App 狀態的第一線。無論是「正在等待網路回應」的轉圈標記,還是需要臨時提示「已加入佇列、傳送成功、傳送失敗」的自製橫幅,都離不開對狀態列的掌控。
最常見的需求是讓使用者知道 App 正在等待網路回應。一行程式碼即可控制那個小小的轉圈圖示:
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES; // 顯示 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; // 隱藏
需要提醒的是,這個指示器是全域共用的。若有多個請求同時進行,建議自行維護一個計數器,只有第一個請求發出時才打開、最後一個請求結束時才關閉,避免互相覆蓋。
狀態列可以透過 UIApplication 提供的介面來修改,例如完全隱藏、更換風格或指定方向。要注意的是,這些變更只在你自己的 App 內生效,一旦離開 App 便會復原。
UIApplication *myApp = [UIApplication sharedApplication];
[myApp setStatusBarHidden:YES animated:YES];
隱藏之後,你的「桌面」可視區域會增加 320×20 的大小。因此最好在建立任何 window 或 view 之前就完成隱藏,否則版面容易錯位。
[myApp setStatusBarStyle:UIStatusBarStyleBlackOpaque];
typedef enum {
UIStatusBarStyleDefault,
UIStatusBarStyleBlackTranslucent,
UIStatusBarStyleBlackOpaque
} UIStatusBarStyle;
[myApp setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:NO];
typedef enum {
UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait, // 直向,垂直向上
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown, // 直向,上下顛倒
UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight, // 裝置逆時針旋轉為橫向
UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft // 裝置順時針旋轉為橫向
} UIInterfaceOrientation;
有些時候系統狀態列無法滿足需求。以新浪微博官方 iOS 客戶端為例,它會在狀態列位置提示訊息正在傳送佇列、傳送成功或失敗。做法是自己定義一個狀態列類別,內含一個顯示文字的 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)。系統定義了三個層級:
const UIWindowLevel UIWindowLevelNormal; const UIWindowLevel UIWindowLevelAlert; const UIWindowLevel UIWindowLevelStatusBar; typedef CGFloat UIWindowLevel;
為了蓋住系統預設的狀態列,把自訂層級往上推一點即可:
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;
}];
}
整體思路並不複雜:用一個層級高於狀態列的 UIWindow,搭配尺寸一致的黑色底與淡入淡出動畫,就能得到接近系統級的提示效果。