解决状态栏和导航不一致的问题

iOS 11 + 可能有时候会碰到状态栏和导航颜色不一致,导航是设置的颜色或者背景不能扩展到状态栏层级下。

DDYNavigationBar.jpg

沉浸式消失了

  • 如果是scrollView自动调整引起的那么
if (@available(iOS 11.0, *)) {
  self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
 } else {
  self.automaticallyAdjustsScrollViewInsets = NO;
}
  • 如果上面不能解决,可能是因为导航在iOS 11+始终44高度造成的 ,那么

写一个分类

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self changeOrignalSEL:@selector(sizeThatFits:) swizzleSEL:@selector(ddy_SizeThatFits:)];
        [self changeOrignalSEL:@selector(layoutSubviews) swizzleSEL:@selector(ddy_LayoutSubviews)];
    });
}

+ (void)changeOrignalSEL:(SEL)orignalSEL swizzleSEL:(SEL)swizzleSEL {
    Method originalMethod = class_getInstanceMethod([self class], orignalSEL);
    Method swizzleMethod = class_getInstanceMethod([self class], swizzleSEL);
    if (class_addMethod([self class], orignalSEL, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod))) {
        class_replaceMethod([self class], swizzleSEL, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzleMethod);
    }
}

- (CGSize)ddy_SizeThatFits:(CGSize)size {
    CGSize navigationBarSize = [self ddy_SizeThatFits:size];
    if (@available(iOS 11, *)) {
        navigationBarSize.height = navigationBarSize.height + [[UIApplication sharedApplication] statusBarFrame].size.height;
    }
    return navigationBarSize;
}

- (void)ddy_LayoutSubviews {
    
    [self ddy_LayoutSubviews];
    if (@available(iOS 11, *)) {
        for (UIView *aView in self.subviews) {
            if ([@[@"_UINavigationBarBackground", @"_UIBarBackground"] containsObject:NSStringFromClass([aView class])]) {
                aView.frame = CGRectMake(0, -CGRectGetMinY(self.frame), CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)+CGRectGetMinY(self.frame));
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。