有些 App 需要在系統狀態列的位置顯示自己的資訊——例如通訊類 App 顯示訊號強度、或長時間任務的提示。做法是自己開一個覆蓋在狀態列之上的視窗,把 UILabel 放進去。
UIWindow *statusWindow = [[UIWindow alloc] initWithFrame:[UIApplication sharedApplication].statusBarFrame]; [statusWindow setWindowLevel:UIWindowLevelStatusBar + 1]; [statusWindow setBackgroundColor:[UIColor clearColor]]; UILabel *statusLabel = [[UILabel alloc] initWithFrame:statusWindow.bounds]; statusLabel.text = @"RSSI:"; statusLabel.textColor = [UIColor blueColor]; statusLabel.textAlignment = NSTextAlignmentCenter; statusLabel.backgroundColor = [UIColor blackColor]; [statusWindow addSubview:statusLabel]; [statusWindow makeKeyAndVisible];
UIWindowLevelStatusBar + 1 讓這個視窗浮在系統狀態列之上,否則會被蓋住。[UIApplication sharedApplication].statusBarFrame 取狀態列實際範圍,換螢幕尺寸或旋轉時都不用改程式。userInteractionEnabled 設為 NO。更新內容時只要改 statusLabel 的 text 即可,不需要重建視窗。要隱藏時,把整個 statusWindow 的 hidden 設為 YES 就能收乾淨。
補充:從 iOS 13 起,狀態列在不同 Scene 下的行為更複雜,這類自繪方案容易與系統樣式衝突。若只是要在導航列或自訂 header 上顯示資訊,直接在自己的 view 裡擺 label 會省事得多;只有真的需要覆蓋系統狀態列時,才值得採用上面的寫法。