设置状态栏背景的颜色(适配iOS 13)

2022-08-09  本文已影响0人  倒着游的鱼

在 iOS 13之前,修改状态栏的背景颜色的方法

- (void) setStatusBarBackgroundColor:(UIColor *)color {
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

但是系统升级到iOS 13 之后,私有KVC iOS不允许valueForKey、setValue: forKey获取和设置私有属性
注意!!:这个时候修改状态栏(电池栏的)在用之前的方法会闪退
解决办法:适配iOS 13 增加代码

- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    if(@available(iOS 13.0, *)) {
        
        static UIView *statusBar =nil;
        if(!statusBar) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                statusBar = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.windowScene.statusBarManager.statusBarFrame] ;
                [[UIApplication sharedApplication].keyWindow addSubview:statusBar];
                statusBar.backgroundColor= color;
                
            });
        }else{
            statusBar.backgroundColor= color;
        }
    }else{
        UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
        if([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
            statusBar.backgroundColor= color;
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读