iOS 13 修改狀態(tài)欄背景顏色

@interface StatusBarTestViewController ()

@property (nonatomic, strong) UIView *customizedStatusBar ;

@end

@implementation StatusBarTestViewController

//跳轉(zhuǎn)到下一級界面時隱藏添加的狀態(tài)欄
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (@available(ios 13.0, *)) {
        if (self.customizedStatusBar) {
            self.customizedStatusBar.hidden = YES;
        }
    }
}
//界面要顯示時取消隱藏添加的狀態(tài)欄 (從下一界面返回時取消隱藏)
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self setupStatusBarColor:[UIColor redColor]];
    });

    if (@available(ios 13.0, *)) {
        if (self.customizedStatusBar) {
            self.customizedStatusBar.hidden = NO;
        }
    }
}

  //設(shè)置狀態(tài)欄顏色
- (void)setupStatusBarColor:(UIColor *)color
{
    if (@available(iOS 13.0, *)) {// iOS 13 不能直接獲取到statusbar 手動添加個view到window上當(dāng)做statusbar背景
          if (!self.customizedStatusBar) {
              //獲取keyWindow
              UIWindow *keyWindow = [self getKeyWindow];
              self.customizedStatusBar = [[UIView alloc] initWithFrame:keyWindow.windowScene.statusBarManager.statusBarFrame];
                  [keyWindow addSubview:self.customizedStatusBar];
          }
      } else {
        self.customizedStatusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
     }
      if ([self.customizedStatusBar respondsToSelector:@selector(setBackgroundColor:)]) {
          self.customizedStatusBar.backgroundColor = color;
      }
}
- (UIWindow *)getKeyWindow
{
    // 獲取keywindow
    NSArray *array = [UIApplication sharedApplication].windows;
    UIWindow *window = [array objectAtIndex:0];
    if (!window.hidden || window.isKeyWindow) { //  判斷取到的window是不是keywidow
        return window;
    }
    //  如果上面的方式取到的window 不是keywidow時  通過遍歷windows取keywindow
    for (UIWindow *window in array) {
        if (!window.hidden || window.isKeyWindow) {
            return window;
        }
    }
    return nil;
}

//界面銷毀時把添加的狀態(tài)欄從window上移除
- (void)dealloc{
    if (@available(ios 13.0, *)) {
        if (self.customizedStatusBar) {
            [self.customizedStatusBar removeFromSuperview];
            self.customizedStatusBar = nil;
        }
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容