iOS DeveloperiOS点点滴滴UI

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

2020-03-24  本文已影响0人  鲲鹏DP
QQ20200324-230722-HD.gif

适配暗夜模式

        iOS13新出现了暗夜模式,苹果新增了一些API方便我们来做适配。这里不做深入,只是稍微总结下。
        适配暗夜模式,无非就是界面显示上的一些变化,暗夜模式下,主题由默认的白色调变为了深色调,相应的,我们的APP在显示上也需要做相应调整。主要包括两个方面:颜色的变化(视图颜色色,字体颜色等)和图片的改变;


/*使用时可以做下进一步封装。*/
  [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;
    }];
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection{
    [super traitCollectionDidChange:previousTraitCollection];
    if ([UITraitCollection currentTraitCollection].userInterfaceStyle !=previousTraitCollection.userInterfaceStyle ) {
        NSLog(@"用户切换了模式,在这里做适配工作");
    }else{
        NSLog(@"用户没有切换模式");
    }
}

\color{red}{关于这种适配方式的几点看法:}


动态换肤(DynamicSkin)

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

使用步骤
pod 'DynamicSkin'
#import "DPDynamicTheme.h"
#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
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
      NSDictionary *dataSource = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"theme" ofType:@"plist"]];
      TestConfig *one = [TestConfig mj_objectWithKeyValues: [dataSource objectForKey:@"one"]];
        [[DPThemeManager manager]pushCurrentThemme:one];
    //这里需要主动设置一套暗夜模式的主题,用户切换时自动替换。如果不设置,需要自己监听暗夜模式是否开启,开启时主动切换到暗夜模式皮肤。
        TestConfig *dark = [TestConfig mj_objectWithKeyValues: [dataSource objectForKey:@"dark"]];
        [[DPThemeManager manager]pushDarkModeTheme:dark];
    return YES;
}
    __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])];
}
-(void)dealloc{
  //identifer需要和当前界面绑定的保持一致
    [[DPThemeManager manager] removeUpdateWithIdentifer:NSStringFromClass([self class])];
}

项目地址

上一篇 下一篇

猜你喜欢

热点阅读