背景
iOS 13 之后,App可以支持黑暗模式,如不需要可以直接禁掉。参考iOS系统中的自带软件的黑暗模式的适配,可以看看 设置 页面在黑暗(dark)模式下和正常(light)模式下的显示,以此参考来对我们自己的App进行黑暗模式的适配。
基础
- UITraitCollection.currentTraitCollection.userInterfaceStyle
判断当时处于哪种模式
if (UITraitCollection.currentTraitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
} else {
}
- [UIColor colorWithDynamicProvider…
返回对应模式下的UIColor对象
[UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
return [UIColor blackColor];
} else {
return [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
}
}];
- traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
模式改变监听
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
[self.tableView reloadData];
}
UITableViewCell
- (void)tableView:(UITableView *)tableView1 willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (UITraitCollection.currentTraitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
cell.backgroundColor = [UIColor systemFillColor];
} else {
cell.backgroundColor = [UIColor whiteColor];
}
}
不同模式下显示不同的颜色,仅仅用上述方法的话,会存在一个漏洞,那就是,切换App到后台,然后切换成另外一种模式,这时候,cell的颜色还是之前的,解决办法是在监听里刷新cell的显示。
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
[self.tableView reloadData];
}
其他的tableView的适配,都大同小异,类似的处理就可以了。
其他
- 导航栏
+ (UIColor *)navigationBackgroundColor {
if (@available(iOS 13.0, *)) {
return [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
return [UIColor blackColor];
} else {
return [UIColor whiteColor];
}
}];
}
return [UIColor whiteColor];
}
…