如何检查iOS/iPadOS中是否启用了暗模式?
从iOS/iPadOS 13开始,提供了深色用户界面样式,类似于macOS Mojave中引入的深色模式.如何检查用户是否已启用系统范围的暗模式?
Starting from iOS/iPadOS 13, a dark user interface style is available, similar to the dark mode introduced in macOS Mojave. How can I check whether the user has enabled the system-wide dark mode?
您应检查UITraitCollection
的userInterfaceStyle
变量,与在tvOS和macOS上相同.
You should check the userInterfaceStyle
variable of UITraitCollection
, same as on tvOS and macOS.
switch traitCollection.userInterfaceStyle {
case .light: //light mode
case .dark: //dark mode
case .unspecified: //the user interface style is not specified
}
您应该使用UIView
的 traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
函数/UIViewController
来检测界面环境的变化(包括用户界面样式的变化).
You should use the traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
function of UIView
/UIViewController
to detect changes in the interface environment (including changes in the user interface style).
来自 Apple开发者文档:
当iOS界面环境更改时,系统调用此方法.根据您的应用需求,在视图控制器和视图中实施此方法,以响应此类更改.例如,当iPhone从纵向旋转为横向时,您可以调整视图控制器的子视图的布局.此方法的默认实现为空.
The system calls this method when the iOS interface environment changes. Implement this method in view controllers and views, according to your app’s needs, to respond to such changes. For example, you might adjust the layout of the subviews of a view controller when an iPhone is rotated from portrait to landscape orientation. The default implementation of this method is empty.
系统默认的UI元素(例如UITabBar
或UISearchBar
)自动适应新的用户界面样式.
System default UI elements (such as UITabBar
or UISearchBar
) automatically adapt to the new user interface style.