有時候需要在系統狀態欄的位置顯示一點自訂資訊,例如「資料更新中」的提示圖。做法是自己開一個覆蓋在狀態欄之上的 UIWindow,把 window level 設得比狀態欄更高,再塞入想要的子視圖。
-(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"];
// 若想用純文字呈現,也可以改用 label:
// UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 100, 20)];
// label.backgroundColor = [UIColor clearColor];
// label.text = @"數據正在刷新";
// [customView addSubview:label];
[statusbarWindow addSubview:customView];
[statusbarWindow makeKeyAndVisible];
}
視窗高度抓 20pt,正好對應狀態欄的高度;背景設為 clearColor 才能透出底下的系統內容。真正讓它能蓋在狀態欄上的是 UIWindowLevelStatusBar + 1.0f 這一行——window level 決定了繪製的層序,只要比狀態欄高一階,就會壓在它上面。
另外記得把 statusbarWindow 存成成員變數並在不用時釋放。這種視窗若沒有妥善管理,容易在切換頁面後殘留或洩漏。實務上也建議只在使用期間才建立、任務結束就關閉,避免長期佔用而干擾使用者的正常操作。
摘自 shijiucdy的專欄