美文网首页
iOS 13 修改状态栏背景颜色

iOS 13 修改状态栏背景颜色

作者: 笑完睡觉 | 来源:发表于2019-10-10 18:13 被阅读0次
@interface StatusBarTestViewController ()

@property (nonatomic, strong) UIView *customizedStatusBar ;

@end

@implementation StatusBarTestViewController

//跳转到下一级界面时隐藏添加的状态栏
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (@available(ios 13.0, *)) {
        if (self.customizedStatusBar) {
            self.customizedStatusBar.hidden = YES;
        }
    }
}
//界面要显示时取消隐藏添加的状态栏 (从下一界面返回时取消隐藏)
- (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;
        }
    }
}

  //设置状态栏颜色
- (void)setupStatusBarColor:(UIColor *)color
{
    if (@available(iOS 13.0, *)) {// iOS 13 不能直接获取到statusbar 手动添加个view到window上当做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;
}

//界面销毁时把添加的状态栏从window上移除
- (void)dealloc{
    if (@available(ios 13.0, *)) {
        if (self.customizedStatusBar) {
            [self.customizedStatusBar removeFromSuperview];
            self.customizedStatusBar = nil;
        }
    }
}

相关文章

网友评论

      本文标题:iOS 13 修改状态栏背景颜色

      本文链接:https://www.haomeiwen.com/subject/ylmapctx.html