ios13 设置状态栏颜色


#import "MainViewController.h"


@interface MainViewController ()

@property (nonatomic, strong) UIView *customizedStatusBar;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
   
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [self setupStatusBarColor:[UIColor redColor]];
}

//设置状态栏颜色
- (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];

     //  判断取到的window是不是keywidow
    if (!window.hidden || window.isKeyWindow) { 
        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;
        }
    }
}



@end

 

你可能感兴趣的:(导航)