iOS13深色模式/暗黑模式导航栏不自动适配的解决方案

iOS13深色模式导航栏不自动适配的解决方案

  • 问题: 进入某一页面后切换当前模式,导航栏的内容不随模式自动变化
  • 猜测: 可能是由于UIBarButtonItem不是继承自UIView,所以在切换时不会主动去设置UIBarButtonItem内部的图片
  • 解决方法: 手动设置一次导航栏内子控件的图片,这里需要注意,不用单独把lightMode与darkMode的图片分离,同一个图片名称,在不同模式下系统会自动去取对应的图片,所以只需要在项目的BaseViewController控制器中切换模式的代理方法 - (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection 中遍历出UIBarButtonItem并进行设置即可解决该问题 代码如下:
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
{
    [super traitCollectionDidChange:previousTraitCollection];
    if (@available(iOS 13.0, *)) {
        // trait发生了改变
        if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) {
            //每次切换模式刷新一次导航栏的UI
            for (UIBarButtonItem *leftItem in self.navigationItem.leftBarButtonItems) {
                [self refreshBarButtonItem:leftItem];
            }
            for (UIBarButtonItem *rightItem in self.navigationItem.rightBarButtonItems) {
                [self refreshBarButtonItem:rightItem];
            }
        }
    }
}
//刷新barbuttonitem的图片(用于修复深色模式不自动切换图片颜色的bug)
- (void)refreshBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    //如果是自定义的按钮
    if ([barButtonItem.customView isKindOfClass:[UIButton class]]) {
        UIButton *button = (UIButton *)(barButtonItem.customView);
        UIImage *image = [UIImage imageNamed:[button.imageView.image accessibilityIdentifier]];//取出图片的名称
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [button setImage:image forState:UIControlStateNormal];
    } else if ([barButtonItem.customView isKindOfClass:[UIImageView class]]) {//如果是自定义的图片
        UIImageView *imageView = (UIImageView *)(barButtonItem.customView);
        UIImage *image = [UIImage imageNamed:[imageView.image accessibilityIdentifier]];
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        imageView.image = image;
    } else {//如果非自定义视图
        UIImage *image = [UIImage imageNamed:[barButtonItem.image accessibilityIdentifier]];
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        barButtonItem.image = image;
    }
}

 

你可能感兴趣的:(iOS13深色模式/暗黑模式导航栏不自动适配的解决方案)