如何检查iOS暗模式? [英] How to Check for iOS Dark Mode?

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

问题描述

•如何在iOS应用中观察黑暗模式状态 •如何应对iOS应用中黑暗模式状态的变化

• How to observe dark mode state in an iOS app • How to react to changes in dark mode state in an iOS app

推荐答案

UIKit已有UITraitCollection已有一段时间了.从iOS 9开始,您可以使用UITraitCollection来查看设备是否支持3D Touch(另一天令人难过的谈话)

UIKit has had UITraitCollection for a while now. Since iOS 9 you could use UITraitCollection to see whether the device supports 3D Touch (a sad conversation for another day)

在iOS 12 中,UITraitCollection获得了一个新属性:支持三种情况:lightdarkunspecified

In iOS 12, UITraitCollection got a new property: var userInterfaceStyle: UIUserInterfaceStyle which supports three cases: light, dark, and unspecified

由于UIViewController继承了UITraitEnvironment,因此您可以访问ViewController的traitCollection.这存储userInterfaceStyle.

Since UIViewController inherits UITraitEnvironment, you have access to the ViewController's traitCollection. This stores userInterfaceStyle.

UITraitEnviroment还具有一些漂亮的协议存根,可帮助您的代码解释状态变化发生的时间(因此,当用户从暗面切换到亮面时,反之亦然).这是一个适合您的编码示例:

UITraitEnviroment also has some nifty protocol stubs that help your code interpret when state changes happen (so when a user switches from the Dark side to the Light side or visa versa). Here's a nice coding example for you:

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if self.traitCollection.userInterfaceStyle == .dark {
            // User Interface is Dark
        } else {
            // User Interface is Light
        }

    }


    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        // Trait collection has already changed
    }

    override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
        // Trait collection will change. Use this one so you know what the state is changing to.
    }
}

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

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