如何检查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获得了一个新属性:light
,dark
和unspecified
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.
}
}