萬盛學電腦網

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

iOS 進階技巧:自定義狀態欄完整實作(支援旋轉動畫)

為什麼要自定義狀態欄?

專案需求:在狀態欄顯示下載進度條。Apple 未開放狀態欄 API,官方文檔也未提及修改 Window Level 的方式。解決方案:建立一個 Window Level 高於系統狀態欄的 UIWindow 子類別,覆蓋在系統狀態欄之上。

Window Level 階層概念

typedef CGFloat UIWindowLevel;
const UIWindowLevel UIWindowLevelNormal;       // 0.0
const UIWindowLevel UIWindowLevelStatusBar;    // 1000.0
const UIWindowLevel UIWindowLevelAlert;        // 2000.0

預設 View 在 UIWindowLevelNormal。系統 Alert 在 UIWindowLevelAlert 所以覆蓋在我們的 View 上。要蓋過系統狀態欄,需設定 windowLevel = UIWindowLevelStatusBar + 1。

完整實作代碼

StatusBarOverlay.h

#import <UIKit/UIKit.h>

@interface StatusBarOverlay : UIWindow {
    UIView *contentView;
    UILabel *textLabel;
}

@property (nonatomic, retain) UIView *contentView;
@property (nonatomic, retain) UILabel *textLabel;

@end

StatusBarOverlay.m

#import "StatusBarOverlay.h"

#define STATUS_BAR_ORIENTATION [UIApplication sharedApplication].statusBarOrientation
#define ROTATION_ANIMATION_DURATION [UIApplication sharedApplication].statusBarOrientationAnimationDuration

@interface StatusBarOverlay()
- (void)initializeToDefaultState;
- (void)rotateStatusBarWithFrame:(NSValue *)frameValue;
- (void)setSubViewHFrame;
- (void)setSubViewVFrame;
@end

@implementation StatusBarOverlay
@synthesize contentView, textLabel;

- (id)init {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        // 關鍵:Window Level 高於系統狀態欄
        self.windowLevel = UIWindowLevelStatusBar + 1;
        self.frame = [UIApplication sharedApplication].statusBarFrame;
        [self setBackgroundColor:[UIColor orangeColor]];
        [self setHidden:NO];

        // 內容視圖
        UIView *_contentView = [[UIView alloc] initWithFrame:self.bounds];
        self.contentView = _contentView;
        [self.contentView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
        [self.contentView setBackgroundColor:[UIColor cyanColor]];
        [self addSubview:self.contentView];
        [_contentView release];

        // 文字標籤
        UILabel *_textLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, CGRectGetWidth(self.frame)-60, CGRectGetHeight(self.frame))];
        self.textLabel = _textLabel;
        [self.textLabel setBackgroundColor:[UIColor blueColor]];
        [self.textLabel setFont:[UIFont systemFontOfSize:12]];
        [self.textLabel setTextAlignment:UITextAlignmentCenter];
        [self.textLabel setTextColor:[UIColor blackColor]];
        [self.textLabel setText:@"自定義的狀態欄 author by jordy"];
        [self.contentView addSubview:self.textLabel];
        [_textLabel release];

        // 監聽螢幕旋轉通知
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(willRotateScreenEvent:)
                                                     name:UIApplicationWillChangeStatusBarFrameNotification
                                                   object:nil];
        [self initializeToDefaultState];
    }
    return self;
}

- (void)initializeToDefaultState {
    CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
    [self rotateStatusBarWithFrame:[NSValue valueWithCGRect:statusBarFrame]];
}

- (void)rotateStatusBarWithFrame:(NSValue *)frameValue {
    CGRect frame = [frameValue CGRectValue];
    UIInterfaceOrientation orientation = STATUS_BAR_ORIENTATION;

    if (orientation == UIDeviceOrientationPortrait) {
        self.transform = CGAffineTransformIdentity;
        [self setSubViewVFrame];
    } else if (orientation == UIDeviceOrientationPortraitUpsideDown) {
        self.transform = CGAffineTransformMakeRotation(M_PI);
        [self setSubViewVFrame];
    } else if (orientation == UIDeviceOrientationLandscapeRight) {
        self.transform = CGAffineTransformMakeRotation((M_PI * (-90.0f) / 180.0f));
        [self setSubViewHFrame];
    } else if (orientation == UIDeviceOrientationLandscapeLeft) {
        self.transform = CGAffineTransformMakeRotation(M_PI * 90.0f / 180.0f);
        [self setSubViewHFrame];
    }

    self.frame = frame;
    [self.contentView setFrame:self.bounds];
}

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

#pragma mark - 螢幕旋轉事件響應
- (void)willRotateScreenEvent:(NSNotification *)notification {
    NSValue *frameValue = [notification.userInfo valueForKey:UIApplicationStatusBarFrameUserInfoKey];
    [self rotateStatusBarAnimatedWithFrame:frameValue];
}

- (void)rotateStatusBarAnimatedWithFrame:(NSValue *)frameValue {
    [UIView animateWithDuration:ROTATION_ANIMATION_DURATION animations:^{
        self.alpha = 0;  // 先淡出
    } completion:^(BOOL finished) {
        [self rotateStatusBarWithFrame:frameValue];  // 旋轉調整
        [UIView animateWithDuration:ROTATION_ANIMATION_DURATION animations:^{
            self.alpha = 1;  // 再淡入
        }];
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [textLabel release]; textLabel = nil;
    [contentView release]; contentView = nil;
    [super dealloc];
}
@end

關鍵設計細節

  1. 初始化必設 hidden = NO:UIWindow 預設隱藏
  2. 旋轉分離處理:自定義狀態欄與 ViewController 旋轉獨立,需先隱藏動畫、調整 Frame、再顯示動畫,避免畫面閃爍
  3. 動態調整 Frame:根據 statusBarFrame 與 statusBarOrientation 即時計算
  4. 進度條動畫:只需修改子視圖 frame.origin.y 即可實現從頂部下拉/收回效果

使用方式

// 在 AppDelegate 或需要處啟動
StatusBarOverlay *statusBarOverlay = [[StatusBarOverlay alloc] init];

專案中用於開機自動下載進度顯示,放在 AppDelegate 初始化最合適。

copyright © 萬盛學電腦網 all rights reserved