若需要在 iOS 狀態欄位置顯示自訂內容,例如下載進度或提示訊息,可以建立一個 windowLevel 高於系統狀態欄的 UIWindow。本文說明實作概念與注意事項。
系統狀態欄的 windowLevel 為 UIWindowLevelStatusBar。若要讓自訂視圖顯示在狀態欄之上,可將自訂 UIWindow 的層級設為:
self.windowLevel = UIWindowLevelStatusBar + 1;
可建立一個繼承自 UIWindow 的 StatusBarOverlay 類別,並在初始化時設定 frame、背景色與子視圖:
self.frame = [UIApplication sharedApplication].statusBarFrame;
self.hidden = NO;
UIView *contentView = [[UIView alloc] initWithFrame:self.bounds];
[self addSubview:contentView];
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, CGRectGetWidth(self.frame) - 60, CGRectGetHeight(self.frame))];
textLabel.font = [UIFont systemFontOfSize:12];
textLabel.textAlignment = NSTextAlignmentCenter;
[contentView addSubview:textLabel];
自訂狀態欄與畫面旋轉是分離的,因此需要監聽狀態欄 frame 變更通知:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(willRotateScreenEvent:)
name:UIApplicationWillChangeStatusBarFrameNotification
object:nil];
在通知中可先隱藏自訂狀態欄,完成旋轉後再顯示,避免畫面跳動。
初始化並保留該物件即可:
StatusBarOverlay *statusBarOverlay = [[StatusBarOverlay alloc] init];
Apple 並未公開狀態欄修改 API,此做法屬於利用 UIWindow 層級的變通方式。在正式專案中使用時,應注意系統版本差異與 App Store 審核風險。