DarkModeAdapter
简介
iOS 暗黑模式适配懒人版
普通模式(light)下:
lightMode.png
暗黑模式(dark)下:
darkMode.png
- 此方式集成简单,代码侵入性小
- 项目颜色统一集中管理,避免杂乱
- 支持关闭暗黑模式适配
- 支持颜色透明度
- 支持其他模式与暗黑模式动态切换(无需在每个页面单独对模式切换进行适配)
- 旧项目改造:
- 如果项目最低支持iOS11.0,那么恭喜你,只需在color assets中配置颜色即可,而且系统会自动调用assets中的当前模式下的颜色,无需额外的代码控制
- 如果项目最低支持小于iOS11.0,那么需在bundle中的plist配置文件中配置颜色
- 需在使用颜色的时候替换成扩展方法中的颜色赋值方法
使用说明
-
1.在项目启动的时候初始化, 此时会把所有颜色都注册好,加载到内存中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. [[AdapterManager sharedInstance] configDarkModeColorBundleName:@"DarkModeAdapter"]; // [AdapterManager sharedInstance].shouldFollowSystemMode = NO; return YES; }
-
2.在给控件赋值颜色的时候调用扩展方法
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor qx_colorNamed:Color_FFFFFF]; self.label.textColor = [UIColor qx_colorNamed:Color_E6B97D]; self.testView.backgroundColor = [UIColor qx_colorNamed:Color_5F9EA0_Opacity]; self.testView.layerShadowColorHex = Color_EE82EE_Shadow; self.testView.layer.shadowOpacity = 1.0; self.testView.layer.shadowRadius = 8.0; self.testView.layer.shadowOffset = CGSizeMake(8.0, 8.0); self.button.backgroundColor = [UIColor qx_colorNamed:Color_FFB700]; self.button.layer.cornerRadius = 20.0; self.button.layerBorderColorHex = Color_90EE90; self.button.layer.borderWidth = 2.0; }
-
至于CoreGraphics中的颜色设置,可以分类中扩展属性进行配置;也可以自行进行单独地动态配置(方案一:在viewDidLayoutSubViews、layoutSubViews等中配置layer层颜色;方案二:普通配置之后,添加系统的模式切换监听方法,在此方法中重新赋值layer层颜色)
// Here you can expand the properties you want @interface UIView (Adapter) /// Config CaLayer BorderColor use Hex String @property(nonatomic, copy) NSString *layerBorderColorHex; /// Config CaLayer BackgroundColor use Hex String @property(nonatomic, copy) NSString *layerBackgroundColorHex; /// Config CaLayer ShadowColor use Hex String @property(nonatomic, copy) NSString *layerShadowColorHex; - (void)viewDidLoad { [super viewDidLoad]; self.button.layer.cornerRadius = 20.0; self.button.layerBorderColorHex = Color_90EE90; self.button.layer.borderWidth = 2.0; }
或者:
- (void)configSubViewsShadow { [self.bgView shadowWithSide:ShadowSideNoTop shadowColorName:BlackShadowColor shadowOpacity:0.4 shadowWidth:4.0 shadowRadius:4.0]; }
- (void)layoutSubviews { [super layoutSubviews]; [self configSubViewsShadow]; }
或者:
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { if (![AdapterManager sharedInstance].shouldFollowSystemMode) return; if (@available(iOS 13.0, *)) { UIApplicationState state = [UIApplication sharedApplication].applicationState; if (state != UIApplicationStateBackground && previousTraitCollection && [self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) { [self configSubViewsShadow]; } } }
至于图标适配
- 在Assets中,Appearance中选择
Any, Dark
,再添加dark下的图标即可;此处不作过多说明。
最后附上demo地址
网友评论