iOS黑暗模式tableViewCell

背景

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];
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Morris_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值