iOS适配灵动岛safeArea顶部高度变化

1,487 阅读1分钟

灵动岛出来后,发现线上iOS应用顶部出现白条现象

截屏2023-02-28 11.31.48.png

我们的应用是嵌套wkwebview做的,之前修改顶部状态栏颜色的代码是这样的

- (void) changeStatusBarColor: (NSString *) hexColor {
    if (@available(iOS 13.0, *)) {
        // iOS 13  弃用keyWindow属性  从所有windowl数组中取
        UIView *statusBar = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.windowScene.statusBarManager.statusBarFrame] ;
        statusBar.backgroundColor = [self colorWithHexString:hexColor];
        [[UIApplication sharedApplication].keyWindow addSubview:statusBar];
    }else{
        UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
        if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
            statusBar.backgroundColor = [self colorWithHexString:hexColor];
        }
    }
}

查了一下发现,是灵动岛的机型系统的statusbar高度和safeArea顶部高度不一致导致的,刘海机型是statusbar和safeArea一样是47,灵动岛机型statusbar高度是54,safeArea顶部高度是59,导致出现高度5的白边

所以适配方案为,修改statusbar高度和safeArea顶部高度一致即可,代码如下

- (void) changeStatusBarColor: (NSString *) hexColor {
    if (@available(iOS 13.0, *)) {
        // iOS 13  弃用keyWindow属性  从所有windowl数组中取
        UIView *statusBar = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.windowScene.statusBarManager.statusBarFrame] ;
        statusBar.backgroundColor = [self colorWithHexString:hexColor];
        // 修改statusBar高度适配灵动岛
        [statusBar setFrame:CGRectMake(statusBar.frame.origin.x, statusBar.frame.origin.y, statusBar.frame.size.width, [UIApplication sharedApplication].keyWindow.safeAreaInsets.top)];
        [[UIApplication sharedApplication].keyWindow addSubview:statusBar];
    }else{
        UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
        if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
            statusBar.backgroundColor = [self colorWithHexString:hexColor];
        }
    }
}

效果达成

截屏2023-02-28 11.47.46.png