Skip to content

Commit c971d5d

Browse files
author
Draveness
committed
Add first chapter for DKNightVersion imp
1 parent fb0ff32 commit c971d5d

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# 成熟的夜间模式解决方案
2+
3+
从开始写 [DKNightVersion](https://github.com/Draveness/DKNightVersion) 这个框架到现在已经将近一年了,目前整个框架的设计也趋于稳定,其实夜间模式的实现就是相当于**多主题和颜色管理**。而最新版本的 [DKNightVersion](https://github.com/Draveness/DKNightVersion) 已经很好的解决了这个问题。
4+
5+
在正式介绍目前版本的实现之前,我会先简单介绍一下 1.0 时代的 DKNightVersion 的实现,为各位读者带来一些新的思路,也确实想梳理一下这个框架是如何演变的。
6+
7+
> 我们会以对 `backgroundColor` 为例说明整个框架的工作原理
8+
9+
## 方法调剂的版本
10+
11+
而如何在不改变原有的架构,甚至不改变原有的代码的基础上,就能为应用优雅地添加夜间模式就成为一个在很多应用开发的过程中不得不面对的一个问题。这也是 1.0 时代的 DKNightVersion 想要实现的目标。
12+
13+
### 使用 nightBackgroundColor
14+
15+
在思考之后,我想到,想要在不改动原有代码的基础上实现夜间模式只能通过在**分类**中添加 `nightBackgroundColor` 这种属性,并且使用方法调剂改变 `backgroundColor` 的 setter 方法。
16+
17+
```objectivec
18+
- (void)hook_setBackgroundColor:(UIColor*)backgroundColor {
19+
if ([DKNightVersionManager currentThemeVersion] == DKThemeVersionNormal) {
20+
[self setNormalBackgroundColor:backgroundColor];
21+
}
22+
[self hook_setBackgroundColor:backgroundColor];
23+
}
24+
```
25+
26+
在当前主题为 `DKThemeVersionNormal` 时,将颜色保存至 `normalBackgroundColor` 属性中,然后在调用原 `backgroundColor` 的 setter 方法,更新视图的颜色。
27+
28+
这时,如果我们在全局修改整个应用的主题时,并不会立刻更新整个应用的颜色。
29+
30+
整个 DKNightVersion 都是由一个 DKNightVersionManager 的单例来管理的,而它的主要只能就是负责改变整个应用的主题、并在主题发生改变时使其它视图更新颜色:
31+
32+
```objectivec
33+
- (void)changeColor:(id <DKNightVersionChangeColorProtocol>)object {
34+
if ([object respondsToSelector:@selector(changeColor)]) {
35+
[object changeColor];
36+
}
37+
if ([object respondsToSelector:@selector(subviews)]) {
38+
if (![object subviews]) {
39+
// Basic case, do nothing.
40+
return;
41+
} else {
42+
for (id subview in [object subviews]) {
43+
// recursive darken all the subviews of current view.
44+
[self changeColor:subview];
45+
if ([subview respondsToSelector:@selector(changeColor)]) {
46+
[subview changeColor];
47+
}
48+
}
49+
}
50+
}
51+
}
52+
```
53+
54+
如果主题更新,那么就会递归地调用 `changeColor:` 方法,刷新全部的视图颜色,而这个方法的实现实在是太过简单:
55+
56+
```objectivec
57+
- (void)changeColor {
58+
if ([DKNightVersionManager currentThemeVersion] == DKThemeVersionNormal) {
59+
self.backgroundColor = self.normalBackgroundColor;
60+
} else {
61+
self.backgroundColor = self.nightBackgroundColor;
62+
}
63+
}
64+
```
65+
66+
上面就是整个框架在 1.0 版本时的实现思路。不过这个版本的 DKNightVersion 在实际应用中会有比较多的问题:
67+
68+
1. 在高速滚动的 `scrollView` 上面来回切换夜间模式,会出现颜色错乱的问题
69+
2. 由于对 `backgroundColor` 属性进行**不合适的**方法调剂,其行为无法预测
70+
2. 无法适配第三方 UI 控件
71+
72+
### DKColorPicker
73+
74+
为了解决 1.0 中的各种问题,我决定在 2.0 版本中放弃对 `nightBackgroundColor` 的使用,并且重新设计底层的实现,转而使用更为**稳定****安全**的方法实现夜间模式。
75+
76+
77+
78+
79+
80+

0 commit comments

Comments
 (0)