如何检测iOS 13中的明暗模式更改? [英] How to detect Light\Dark mode change in iOS 13?

查看:198
本文介绍了如何检测iOS 13中的明暗模式更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些用户界面设置无法自动使用,暗/亮模式更改为UIColor.例如图层中的shadow.因为我需要在暗和亮模式下删除阴影并添加阴影,所以我需要在某处放置updateShadowIfNeeded()函数.我知道如何检测当前的模式:

Some of the UI setups not working automatically with the Dark/Light mode change as the UIColor. For example shadow in layer. As I need to remove and drop shadow in dark and light mode, I need somewhere to put updateShadowIfNeeded() function. I know how to detect what is the mode currently:

func dropShadowIfNeeded() {
    switch traitCollection.userInterfaceStyle {
    case .dark: removeShadow()
    case .light: dropShadowIfNotDroppedYet()
    default: assertionFailure("Unknown userInterfaceStyle")
    }
}

现在,我将函数放在layoutSubviews中,因为每次外观更改时都会调用该函数:

Now I put the function inside the layoutSubviews, since it gets called every time appearance change:

override func layoutSubviews() {
    super.layoutSubviews()
    dropShadowIfNeeded()
}

但是此功能被称为很多.仅当userInterfaceStyle更改时才触发的正确功能是什么?

But this function is getting called A LOT. What is the proper function to trigger only if userInterfaceStyle changed?

推荐答案

我在 WWDC 2019-会议214 大约在23:30结束.

I found the answer on WWDC 2019 - Session 214 around 23:30.

正如我预期的那样,包括更改颜色时,此函数被调用很多.除了ViewControllerpresentationController的许多其他功能之外.但是有一些专门设计的功能在所有View代表中都有相似的签名.

As I expected, this function is getting called a lot including when colors changing. Along side with many other functions for ViewController and presentationController. But there is some especial function designed for that has a similar signature in all View representers.

看看该会话中的这张图片:

Take a look at this image from that session:

灰色:打电话,但不适合我的问题,绿色:专为此设计

所以我应该调用它并在此函数中检查它:

So I should call it and check it inside this function:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
        dropShadowIfNeeded()
    }
}

这将确保每次更改仅被调用一次.

This will guarantee to be called just once per change.

这篇关于如何检测iOS 13中的明暗模式更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆