@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;
}
}
}
网友评论