注册

iOS动态换肤-支持暗夜模式

适配暗夜模式

iOS13新出现了暗夜模式,苹果新增了一些API方便我们来做适配。这里不做深入,只是稍微总结下。

适配暗夜模式,无非就是界面显示上的一些变化,暗夜模式下,主题由默认的白色调变为了深色调,相应的,我们的APP在显示上也需要做相应调整。主要包括两个方面:颜色的变化(视图颜色色,字体颜色等)和图片的改变;

  • 关于颜色改变:UIcolor新增了一个分类\color{red}{UIColor (DynamicColors)},提供了动态color的API。通过特征收集器traitCollection,可以动态判断当前手机的一些界面特征信息。

/*使用时可以做下进一步封装。*/
[UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
UIColor *color = [UIColor lightGrayColor];
if (@available(iOS 13.0,*)) {
if (traitCollection.userInterfaceStyle ==UIUserInterfaceStyleDark ) {
color =[UIColor blackColor];//dark
}else if(traitCollection.userInterfaceStyle ==UIUserInterfaceStyleLight){
color =[UIColor lightGrayColor];//light
}
}
return color;
}];
  • 关于图片:可以在Assets.xcassets中给每一套图片设置对应的模式,系统自动根据当前的模式取用相应的图片;

6a9842bf1e76c0f7590e422ee3e1ab80.png

  • 监听模式的改变:做好以上两点只能部分满足需求,很多时候我们需要确切的知道当前的模式,并且知道用户什么时候切换的模式;

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection{
[super traitCollectionDidChange:previousTraitCollection];
if ([UITraitCollection currentTraitCollection].userInterfaceStyle !=previousTraitCollection.userInterfaceStyle ) {
NSLog(@"用户切换了模式,在这里做适配工作");
}else{
NSLog(@"用户没有切换模式");
}
}

关于这种适配方式的几点看法:

  • 工作繁琐,代码杂乱。界面如果需要做一些定制化的改变,就需要监听模式的改变,可能出现一个界面适配的代码出现在好几个地方。

  • 扩展性不高。现在出现了一个暗夜模式,将来会不会再有其他模式?如果APP本来就有几套主题,那么适配起来更加繁琐杂乱。

  • 细细想来,适配暗夜模式,不就是切换主题吗,单独给暗夜模式弄一套对应皮肤就完了。下面看看,如何给APP便捷高效、扩展性性高地换肤。

动态换肤(DynamicSkin)
代码简洁,便于维护;
自动适配暗夜模式,不需要自己每个界面去监听模式的切换;

使用步骤
1.引入框架,导入头文件
手动引入或者通过CocoaPods

pod 'DynamicSkin'
#import "DPDynamicTheme.h"

2.配置模型
继承DPThemeConfig,根据自己的需求,配置相应字段即可。

#import "DPThemeConfig.h"

NS_ASSUME_NONNULL_BEGIN

@interface TestConfig : DPThemeConfig
@property(nonatomic,copy)NSString*color1;
@property(nonatomic,copy)NSString*color2;
@property(nonatomic,copy)NSString*img1;
@property(nonatomic,copy)NSString*tabOne;
@property(nonatomic,copy)NSString*tabTwo;
@property(nonatomic,copy)NSString*tabThree;
@property(nonatomic,copy)NSString*tabTextColorNormal;
@property(nonatomic,copy)NSString*tabTextColorSelect;
@property(nonatomic,copy)NSString*state;
@end

NS_ASSUME_NONNULL_END

3.设置默认主题

__weak typeof (self)weakSelf = self;
//用户切换暗夜模式,或则主动切换pushCurrentThemme:,会触发该回调
[self tz_dynamicTheme:^(TestConfig * _Nullable config) {
[weakSelf.image sd_setImageWithURL:[NSURL URLWithString:config.img1]];
weakSelf.statelabel.text = config.state;
} WithIdentifier:NSStringFromClass([self class])];
}

4.数据绑定

__weak typeof (self)weakSelf = self;
//用户切换暗夜模式,或则主动切换pushCurrentThemme:,会触发该回调
[self tz_dynamicTheme:^(TestConfig * _Nullable config) {
[weakSelf.image sd_setImageWithURL:[NSURL URLWithString:config.img1]];
weakSelf.statelabel.text = config.state;
} WithIdentifier:NSStringFromClass([self class])];
}

5.销毁不需要的回调

-(void)dealloc{
//identifer需要和当前界面绑定的保持一致
[[DPThemeManager manager] removeUpdateWithIdentifer:NSStringFromClass([self class])];
}

转自:https://www.jianshu.com/p/50f24d5af4cd

0 个评论

要回复文章请先登录注册