您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

如何實作 iOS 自訂狀態列

編輯:iOS 開發綜合

有些 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。
  • 記得持有:在 ARC 環境下,這個 statusWindow 需要有一個強參照(例如存成 property),否則會被回收而消失。

更新內容時只要改 statusLabel 的 text 即可,不需要重建視窗。要隱藏時,把整個 statusWindow 的 hidden 設為 YES 就能收乾淨。

補充:從 iOS 13 起,狀態列在不同 Scene 下的行為更複雜,這類自繪方案容易與系統樣式衝突。若只是要在導航列或自訂 header 上顯示資訊,直接在自己的 view 裡擺 label 會省事得多;只有真的需要覆蓋系統狀態列時,才值得採用上面的寫法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved