有時候你需要在系統狀態欄的位置顯示自己的訊息——「資料更新中」、「已同步」、「離線模式」。系統不允許直接改寫狀態欄內容,但可以用一個浮動的 UIWindow 疊在它上面。本文提供兩種實作方式。
- (void)setRefreshWindow
{
CGRect frame = CGRectMake(0.0, 0.0, 320.0, 20.0);
statusbarWindow = [[UIWindow alloc] initWithFrame:frame];
[statusbarWindow setBackgroundColor:[UIColor clearColor]];
[statusbarWindow setWindowLevel:UIWindowLevelStatusBar + 1.0f];
// 放入自訂子視圖
UIImageView *customView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 0, 120, 18)];
customView.image = [UIImage imageNamed:@"數據刷新欄.png"];
[statusbarWindow addSubview:customView];
[statusbarWindow makeKeyAndVisible];
}
這種寫法適合「只要蓋一張圖上去」的簡單場景。若想顯示文字,把 UIImageView 換成 UILabel 即可(原範例中就有被註解掉的 label 版本)。
如果多個頁面都要用,封裝成一個類別會乾淨得多。
XYCustomStatusBar.h
#import <UIKit/UIKit.h>
@interface XYCustomStatusBar : UIWindow
{
UILabel *_messageLabel;
}
- (void)showStatusMessage:(NSString *)message;
- (void)hide;
@end
XYCustomStatusBar.m
#import "XYCustomStatusBar.h"
@implementation XYCustomStatusBar
- (void)dealloc
{
[super dealloc];
[_messageLabel release], _messageLabel = nil;
}
- (id)init
{
self = [super init];
if (self) {
// 對齊系統狀態欄的位置與尺寸
self.frame = [UIApplication sharedApplication].statusBarFrame;
self.backgroundColor = [UIColor blackColor];
// 關鍵:windowLevel 決定顯示層次
self.windowLevel = UIWindowLevelStatusBar + 1.0f;
_messageLabel = [[UILabel alloc] initWithFrame:self.bounds];
[_messageLabel setTextColor:[UIColor whiteColor]];
[_messageLabel setTextAlignment:NSTextAlignmentRight];
[_messageLabel setBackgroundColor:[UIColor clearColor]];
[self addSubview:_messageLabel];
}
return self;
}
- (void)showStatusMessage:(NSString *)message
{
self.hidden = NO;
self.alpha = 1.0f;
_messageLabel.text = @"";
CGSize totalSize = self.frame.size;
// 先把高度壓成 0,再動畫展開,形成「往下拉出」的效果
self.frame = (CGRect){ self.frame.origin, 0, totalSize.height };
[UIView animateWithDuration:0.5 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;
}];
}
@end
在 iOS 中,windowLevel 決定 UIWindow 的顯示層次。預設值為 UIWindowLevelNormal(即 0.0)。系統狀態欄所處的層級是 UIWindowLevelStatusBar(通常為 1000),因此若我們的視窗停在 Normal 層級,就會被狀態欄蓋住,什麼也看不到。
把自訂視窗設為 UIWindowLevelStatusBar + 1.0f,它就位於狀態欄之上,這正是整段程式碼能生效的原因。同理,若要蓋在警示對話框之上,就得使用更高的 UIWindowLevelAlert。
記憶體管理。上面的範例使用 MRC(手動參考計數)語法,含 retain/release。在 ARC 專案中請移除 [super dealloc] 與 release 呼叫。
記得隱藏。自訂視窗一旦 makeKeyAndVisible 就會持續存在。若忘了呼叫 hide,它會蓋住狀態欄區域,讓使用者無法點擊(例如無法下拉通知中心)。
不要搶走 key window。用 makeKeyAndVisible 會讓這個視窗成為 key window,可能導致鍵盤或輸入框行為異常。若只是顯示訊息,改用 self.hidden = NO 而不呼叫 makeKeyAndVisible 更安全。
非同步處理時的 UI 更新。顯示訊息的呼叫若來自背景佇列,務必切回主執行緒,否則動畫不會生效甚至崩潰。
更現代的替代做法。這類「短暫提示」的需求,如今更推薦使用 MBProgressHUD、SVProgressHUD 等成熟元件,或直接採用 iOS 的 NSActivityIndicatorView 搭配自訂浮層,能避免自己維護 window level 的複雜度。