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

iOS 自定義狀態欄:建立高於系統狀態欄的 UIWindow

編輯:iOS 開發綜合

若需要在 iOS 狀態欄位置顯示自訂內容,例如下載進度或提示訊息,可以建立一個 windowLevel 高於系統狀態欄的 UIWindow。本文說明實作概念與注意事項。

1. Window Level 概念

系統狀態欄的 windowLevel 為 UIWindowLevelStatusBar。若要讓自訂視圖顯示在狀態欄之上,可將自訂 UIWindow 的層級設為:

self.windowLevel = UIWindowLevelStatusBar + 1;

2. 建立 StatusBarOverlay

可建立一個繼承自 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];

3. 處理旋轉

自訂狀態欄與畫面旋轉是分離的,因此需要監聽狀態欄 frame 變更通知:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(willRotateScreenEvent:)
                                             name:UIApplicationWillChangeStatusBarFrameNotification
                                           object:nil];

在通知中可先隱藏自訂狀態欄,完成旋轉後再顯示,避免畫面跳動。

4. 使用方式

初始化並保留該物件即可:

StatusBarOverlay *statusBarOverlay = [[StatusBarOverlay alloc] init];

5. 注意事項

Apple 並未公開狀態欄修改 API,此做法屬於利用 UIWindow 層級的變通方式。在正式專案中使用時,應注意系統版本差異與 App Store 審核風險。

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