iOS DarkMode适配

3,390 阅读6分钟

iOS13中为我们带来了系统级别的暗黑模式。

而我们居然没能第一时间,系统全面的在我们项目中适配,实在是一大遗憾。

现在我们依然再等待相关UI标准的输出,但是在工程和代码层面,我们已经做好了准备。

下面,就让我们来熟悉一下怎么优雅又全面系统的适配DarkMode吧。

一、标准的制定

DarkMode的核心是颜色的制定。

我们需要将正常模式的颜色一一对应到DarkMode的颜色。

虽然核心是颜色,但是也牵扯到图片的转换,图片的本质也是色彩。

此部分工作,主要需要UI同学来制定。

一旦将我们的规则,或者标准制定完成,那么后续主要工作,主要精力依然在正常模式下。

通过转换规则,则可一一对应到暗黑模式下。

二、系统工程

UITraitCollection

在 iOS 13 中,我们可以通过 UITraitCollection 来判断当前系统的模式。UIView 和 UIViewController 、UIScreen、UIWindow 都已经遵从了UITraitEnvironment 这个协议,因此这些类都拥有一个叫做 traitCollection 的属性。

当DarkMode和正常模式来回切换的时候,会按照以下规则触发以下方法:

KDPfaQ.png

其中,核心的UIColor则会遵从以下方法:

[UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return lightColor;
            }else {
                return darkColor;
            }
        }];

而UIColor动态颜色block的调用有以下条件:

只有当UIColor对象赋值给相应的UIColor对象时,才会调用动态切换的block。

如:

UIColor *backColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return lightColor;
            }else {
                return darkColor;
            }
        }];
self.view.backgroundColor = backColor;

而,例如UIColor转换为CGColor,或者利用UIColor生成图片的方式,是无法通过UIColorDynamicProvider转换的。

对于系统配置来说,我们可以应用以下方法,来动态根据模式变化相关内容:

系统颜色 iOS13支持

在 iOS 13中,苹果引入了全新系统颜色,系统颜色是动态的,会根据当前系统是默认模式还是暗黑模式动态调整颜色。

苹果还提供了一组动态的灰度颜色。

KDP2qS.png

**系统语义化颜色 **iOS13支持

KDieJA.png

Assets 配置 iOS11支持

KDPWVg.png

通过Asset我们可以使用管理颜色,也可以管理图片,来达到动态切换。

三、我们的方案

根据系统的规则,并且结合我们的工程,我们需要进行以下的区分。

我们管理颜色全部使用代码来进行,尽量不使用Asset。

KDPcKf.png

我使用了以下三个类,来整体管理我们的UI效果。

YGUIMannger

@implementation YGUIManager
/// 目前是否是暗黑模式
+ (BOOL)isDarkMode {
    if (@available(iOS 13.0, *)) {
        return (UITraitCollection.currentTraitCollection.userInterfaceStyle == UIUserInterfaceStyleDark);
    }
    return NO;
}

/// 会员金色渐变按钮
+ (UIButton *)vipGradientLayerBtn:(CGRect)frame {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = frame;
    [btn setTitleColor:RGB(0x784720) forState:UIControlStateNormal];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    btn.layer.cornerRadius = CGRectGetHeight(frame)/2;

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = btn.bounds;
    gradient.startPoint = CGPointMake(0, 0.5);
    gradient.endPoint = CGPointMake(1, 0.5);
    gradient.colors = [NSArray arrayWithObjects:
                       (id)RGB(0xfcdeb4).CGColor,
                       (id)RGB(0xdaba87).CGColor, nil];
    gradient.cornerRadius = CGRectGetHeight(frame)/2;
    [btn.layer insertSublayer:gradient atIndex:0];
    return btn;
}

@end

此类主要用来书写统一控件,以及一些统一方法。

YGColor

@implementation YGColor
/// 适配暗黑模式得到颜色,项目中所有颜色必须通过此方法
+ (YGColor *)colorWithNormalColor:(UIColor *)normalColor darkColor:(UIColor *)darkColor {
    if (!normalColor) {
        normalColor = [UIColor whiteColor];
    }
    if (@available(iOS 13.0, *)) {
        if (!darkColor) {
            return (YGColor *)normalColor;
        }
        return (YGColor *)[UIColor colorWithDynamicProvider:^UIColor *_Nonnull (UITraitCollection *_Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
                return darkColor;
            } else {
                return normalColor;
            }
        }];
    } else {
        return (YGColor *)normalColor;
    }
}

/// 适配暗黑模式下的渐变色
+ (YGColor *)colorWithGradientNormalColors:(NSArray *)gradientNormalColors gradientDarkColors:(NSArray *)gradientDarkColors {
    YGColor *color = [YGColor new];
    if (!IS_ARRAY(gradientNormalColors)) {
        gradientNormalColors = [NSArray arrayWithObject:[UIColor whiteColor]];
    }
    if (!IS_ARRAY(gradientDarkColors)) {
        gradientDarkColors = gradientNormalColors;
    }
    color.gradientNormalColors = gradientNormalColors;
    color.gradientDarkColors = gradientDarkColors;
    return color;
}

@end

此类,主要用来管理项目中所有的颜色。

目前主要有两个方法,一个单色,一个渐变色。

而,在此基础上,定义了两个Define,方便调用:

#define kYGAllColor(nColor,dColor) [YGColor colorWithNormalColor:nColor darkColor:dColor]

#define kYGAllGradientColor(nColors,dColors) [YGColor colorWithGradientNormalColors:nColors gradientDarkColors:dColors]

通过YGColor,可以创建项目中使用的所有动态色彩。

Category

@implementation UIView (YGUIManager)
+ (void)load {
    if (@available(iOS 13.0, *)) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            Method presentM = class_getInstanceMethod(self.class, @selector(traitCollectionDidChange:));
            Method presentSwizzlingM = class_getInstanceMethod(self.class, @selector(dy_traitCollectionDidChange:));

            method_exchangeImplementations(presentM, presentSwizzlingM);
        });
    }
}

- (void)dy_traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    if (self.didChangeTraitCollection) {
        self.didChangeTraitCollection(self.traitCollection);
    }
    [self dy_traitCollectionDidChange:previousTraitCollection];
}

- (void)setDidChangeTraitCollection:(void (^)(UITraitCollection *))didChangeTraitCollection {
    objc_setAssociatedObject(self, @"YGViewDidChangeTraitCollection", didChangeTraitCollection, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)(UITraitCollection *))didChangeTraitCollection {
    return objc_getAssociatedObject(self, @"YGViewDidChangeTraitCollection");
}

/// 适配暗黑模式layer的back颜色,项目中必须通过此方法
- (void)setLayerBackColor:(YGColor *)color {
    @yg_weakify(self);
    [self setLayerColor:color changeColor:^(CGColorRef layerColor) {
        @yg_strongify(self);
        self.layer.backgroundColor = layerColor;
    }];
}

/// 适配暗黑模式layer的Border颜色,项目中必须通过此方法
- (void)setLayerBorderColor:(YGColor *)color {
    @yg_weakify(self);
    [self setLayerColor:color changeColor:^(CGColorRef layerColor) {
        @yg_strongify(self);
        self.layer.borderColor = layerColor;
    }];
}

/// 适配暗黑模式layer的shadow颜色,项目中必须通过此方法
- (void)setLayerShadowColor:(YGColor *)color {
    @yg_weakify(self);
    [self setLayerColor:color changeColor:^(CGColorRef layerColor) {
        @yg_strongify(self);
        self.layer.shadowColor = layerColor;
    }];
}

/// color一定是包含暗黑模式的color
- (void)setLayerColor:(YGColor *)color changeColor:(void (^)(CGColorRef layerColor))changeColor {
    if (@available(iOS 13.0, *)) {
        if (changeColor) {
            changeColor([color resolvedColorWithTraitCollection:self.traitCollection].CGColor);
        }
        self.didChangeTraitCollection = ^(UITraitCollection *traitCollection) {
            if (changeColor) {
                changeColor([color resolvedColorWithTraitCollection:traitCollection].CGColor);
            }
        };
    } else {
        // Fallback on earlier versions
        if (changeColor) {
            changeColor(color.CGColor);
        }
    }
}

/// color一定是包含暗黑模式的color
- (void)setGradientColor:(CAGradientLayer *)layer color:(YGColor *)color {
    if (@available(iOS 13.0, *)) {
        if (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
            layer.colors = color.gradientDarkColors;
        } else {
            layer.colors = color.gradientNormalColors;
        }
        self.didChangeTraitCollection = ^(UITraitCollection *traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
                layer.colors = color.gradientDarkColors;
            } else {
                layer.colors = color.gradientNormalColors;
            }
        };
    } else {
        layer.colors = color.gradientNormalColors;
    }
}

@end

@implementation UIImageView (YGUIManager)
/// 适配暗黑模式 使用路径生成的image
- (void)setImageWithNormalImagePath:(NSString *)normalImagePath darkImagePath:(NSString *)darkImagePath {
    if (!normalImagePath
        || [normalImagePath isEqualToString:@""]) {
        return;
    }
    UIImage *normalImage = [UIImage imageWithContentsOfFile:normalImagePath];
    if (@available(iOS 13.0, *)) {
        if (!darkImagePath
            || [darkImagePath isEqualToString:@""]) {
            darkImagePath = normalImagePath;
        }
        UIImage *darkImage = [UIImage imageWithContentsOfFile:darkImagePath];
        if (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
            self.image = darkImage;
        } else {
            self.image = normalImage;
        }

        // UIImageView不会走traitCollectionDidChange
        UIView *superView = self.superview;
        if ([superView isKindOfClass:[UIImageView class]]) {
            superView = superView.superview;
        }
        @yg_weakify(self);
        superView.didChangeTraitCollection = ^(UITraitCollection *traitCollection) {
            @yg_strongify(self);
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
                self.image = darkImage;
            } else {
                self.image = normalImage;
            }
        };
    } else {
        self.image = normalImage;
    }
}

/// 适配暗黑模式 使用颜色生成的image
- (void)setImageWithColor:(YGColor *)color {
    if (@available(iOS 13.0, *)) {
        self.image = [UIImage imageWithColor:[color resolvedColorWithTraitCollection:self.traitCollection]];
        // UIImageView不会走traitCollectionDidChange
        UIView *superView = self.superview;
        if ([superView isKindOfClass:[UIImageView class]]) {
            superView = superView.superview;
        }
        @yg_weakify(self);
        superView.didChangeTraitCollection = ^(UITraitCollection *traitCollection) {
            @yg_strongify(self);
            self.image = [UIImage imageWithColor:[color resolvedColorWithTraitCollection:traitCollection]];
        };
    } else {
        self.image = [UIImage imageWithColor:color];
    }
}

@end

@implementation UIButton (YGUIManager)
/// 适配暗黑模式 使用路径生成的image
- (void)setImageWithNormalImagePath:(NSString *)normalImagePath darkImagePath:(NSString *)darkImagePath forState:(UIControlState)state {
    if (!normalImagePath
        || [normalImagePath isEqualToString:@""]) {
        return;
    }
    UIImage *normalImage = [UIImage imageWithContentsOfFile:normalImagePath];
    if (@available(iOS 13.0, *)) {
        if (!darkImagePath
            || [darkImagePath isEqualToString:@""]) {
            darkImagePath = normalImagePath;
        }
        UIImage *darkImage = [UIImage imageWithContentsOfFile:darkImagePath];
        if (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
            [self setImage:darkImage forState:state];
        } else {
            [self setImage:normalImage forState:state];
        }
        @yg_weakify(self);
        self.didChangeTraitCollection = ^(UITraitCollection *traitCollection) {
            @yg_strongify(self);
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
                [self setImage:darkImage forState:state];
            } else {
                [self setImage:normalImage forState:state];
            }
        };
    } else {
        [self setImage:normalImage forState:state];
    }
}

/// 适配暗黑模式 使用颜色生成的image
- (void)setImageWithColor:(YGColor *)color size:(CGSize)size forState:(UIControlState)state {
    if (@available(iOS 13.0, *)) {
        [self setImage:[UIImage imageWithColor:[color resolvedColorWithTraitCollection:self.traitCollection] size:size] forState:state];
        @yg_weakify(self);
        self.didChangeTraitCollection = ^(UITraitCollection *traitCollection) {
            @yg_strongify(self);
            [self setImage:[UIImage imageWithColor:[color resolvedColorWithTraitCollection:traitCollection]] forState:state];
        };
    } else {
        [self setImage:[UIImage imageWithColor:color] forState:state];
    }
}

/// 适配暗黑模式 使用路径生成的image
- (void)setBackgroundImageWithNormalImagePath:(NSString *)normalImagePath darkImagePath:(NSString *)darkImagePath forState:(UIControlState)state {
    if (!normalImagePath
        || [normalImagePath isEqualToString:@""]) {
        return;
    }
    UIImage *normalImage = [UIImage imageWithContentsOfFile:normalImagePath];
    if (@available(iOS 13.0, *)) {
        if (!darkImagePath
            || [darkImagePath isEqualToString:@""]) {
            darkImagePath = normalImagePath;
        }
        UIImage *darkImage = [UIImage imageWithContentsOfFile:darkImagePath];
        if (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
            [self setBackgroundImage:darkImage forState:state];
        } else {
            [self setBackgroundImage:normalImage forState:state];
        }
        @yg_weakify(self);
        self.didChangeTraitCollection = ^(UITraitCollection *traitCollection) {
            @yg_strongify(self);
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
                [self setBackgroundImage:darkImage forState:state];
            } else {
                [self setBackgroundImage:normalImage forState:state];
            }
        };
    } else {
        [self setBackgroundImage:normalImage forState:state];
    }
}

/// 适配暗黑模式 使用颜色生成的image
- (void)setBackgroundImageWithColor:(YGColor *)color forState:(UIControlState)state {
    if (@available(iOS 13.0, *)) {
        [UIImage imageWithColor:[color resolvedColorWithTraitCollection:self.traitCollection] completion:^(UIImage *image) {
            [self setBackgroundImage:image forState:state];
        }];
        @yg_weakify(self);
        self.didChangeTraitCollection = ^(UITraitCollection *traitCollection) {
            @yg_strongify(self);
            [self setBackgroundImage:[UIImage imageWithColor:[color resolvedColorWithTraitCollection:traitCollection]] forState:state];
        };
    } else {
        [self setBackgroundImage:[UIImage imageWithColor:color] forState:state];
    }
}

@end

其中,我们使用了一个UIView的method swizzling,主要目的为将UIView切换DarkMode所调用的方法,转换为Block,方面外部调用。

主要处理,无法使用UIColor动态处理的情况。

而基于此方法,我们分别创建了:

  1. UIView
  2. UIImageView
  3. UIButton

的Category,用来处理无法跟随动态切换的情况。

而其中使用的Color,一定为YGColor,颜色永远通过YGColor管理。

否则,我们处理此种情况会非常麻烦,需要在每一个顶层View的traitCollectionDidChange来管理其subview的变换规则。

四、写在最后

相信通过以上方法,可以覆盖到我们APP中80%的情况,在标准一定的情况下,完全可以坐到代码规整并优雅的一键切换。

Let’s think!