且构网

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

如何检查iOS/iPadOS中是否启用了暗模式?

更新时间:2023-12-04 19:34:58

您应检查UITraitCollectionuserInterfaceStyle变量,与在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元素(例如UITabBarUISearchBar)自动适应新的用户界面样式.

System default UI elements (such as UITabBar or UISearchBar) automatically adapt to the new user interface style.