且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在iOS中检查暗模式?

更新时间:2023-12-04 19:57:04

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.
    }
}