萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 自定義狀態欄實現原理與代碼解析:覆蓋系統 Status Bar 的 Window Level 技巧

核心原理:Window Level 層級競爭

iOS 窗口層級常量:

  • UIWindowLevelNormal = 0.0(普通應用窗口)
  • UIWindowLevelStatusBar = 1000.0(系統狀態欄)
  • UIWindowLevelAlert = 2000.0(系統彈窗)

關鍵洞察:創建一個 UIWindow 子類,將其 windowLevel = UIWindowLevelStatusBar + 1,即可覆蓋系統狀態欄之上,實現自定義狀態欄內容(如網絡狀態、錄音指示、導航提示等)。

完整實現:StatusBarOverlay 類

頭文件

@interface StatusBarOverlay : UIWindow
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UILabel *textLabel;
@end

實現文件關鍵邏輯

@implementation StatusBarOverlay

- (instancetype)init {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        // 1. 關鍵:層級高於系統狀態欄
        self.windowLevel = UIWindowLevelStatusBar + 1;
        // 2. 初始 frame = 系統狀態欄 frame
        self.frame = [UIApplication sharedApplication].statusBarFrame;
        self.backgroundColor = [UIColor orangeColor];
        self.hidden = NO;

        // 3. 內容視圖自動適配寬度
        UIView *content = [[UIView alloc] initWithFrame:self.bounds];
        content.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        content.backgroundColor = [UIColor cyanColor];
        self.contentView = content;
        [self addSubview:content];

        // 4. 文字標籤
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, CGRectGetWidth(self.frame)-60, CGRectGetHeight(self.frame))];
        label.backgroundColor = [UIColor blueColor];
        label.font = [UIFont systemFontOfSize:12];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.text = @"自定義的狀態欄 author by jordy";
        self.textLabel = label;
        [content addSubview:label];

        // 5. 監聽狀態欄 frame 變化(旋轉、電話欄、熱點欄)
        [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(willRotateScreenEvent:)
            name:UIApplicationWillChangeStatusBarFrameNotification
            object:nil];

        [self initializeToDefaultState];
    }
    return self;
}

// 根據設備方向調整 transform 與子視圖 frame
- (void)rotateStatusBarWithFrame:(NSValue *)frameValue {
    CGRect frame = [frameValue CGRectValue];
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

    if (orientation == UIInterfaceOrientationPortrait) {
        self.transform = CGAffineTransformIdentity;
        [self setSubViewVFrame];
    } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
        self.transform = CGAffineTransformMakeRotation(M_PI);
        [self setSubViewVFrame];
    } else if (orientation == UIInterfaceOrientationLandscapeRight) {
        self.transform = CGAffineTransformMakeRotation(-M_PI_2);
        [self setSubViewHFrame];
    } else if (orientation == UIInterfaceOrientationLandscapeLeft) {
        self.transform = CGAffineTransformMakeRotation(M_PI_2);
        [self setSubViewHFrame];
    }

    self.frame = frame;
    self.contentView.frame = self.bounds;
}

- (void)setSubViewVFrame { // 直向
    self.textLabel.frame = CGRectMake(30, 0, 748-60, 20);
}
- (void)setSubViewHFrame { // 橫向
    self.textLabel.frame = CGRectMake(30, 0, 1024-60, 20);
}

// 動畫過渡:淡出 → 變換 → 淡入
- (void)willRotateScreenEvent:(NSNotification *)note {
    NSValue *frameValue = note.userInfo[UIApplicationStatusBarFrameUserInfoKey];
    [self rotateStatusBarAnimatedWithFrame:frameValue];
}

- (void)rotateStatusBarAnimatedWithFrame:(NSValue *)frameValue {
    [UIView animateWithDuration:[UIApplication sharedApplication].statusBarOrientationAnimationDuration animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self rotateStatusBarWithFrame:frameValue];
        [UIView animateWithDuration:[UIApplication sharedApplication].statusBarOrientationAnimationDuration animations:^{
            self.alpha = 1;
        }];
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

使用方式

// AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.statusBarOverlay = [[StatusBarOverlay alloc] init]; // 強引用持有
    [self.statusBarOverlay makeKeyAndVisible]; // 關鍵:使窗口可見並接收事件
    return YES;
}

現代替代方案(iOS 13+)

  • UIStatusBarManager + UIStatusBarStyle:官方 API 控制樣式(暗/亮/內容顏色)
  • Navigation Bar Appearance:iOS 13+ UINavigationBarAppearance 統一配置導航欄背景、標題、狀態欄樣式
  • SwiftUI:.statusBar(hidden:)、.statusBarStyle()

遺留項目維護提示:Window Level 方案在 iOS 13+ 仍可工作,但可能與新導航欄外觀系統衝突,建議漸進遷移至官方 API。

copyright © 萬盛學電腦網 all rights reserved