iOS13引入了暗黑模式(Dark Appearance)。
模拟器设置暗黑模式:在“设置”-“开发者”中打开“Dark Appearance”。
真机设置暗黑模式:在“设置”-“显示与亮度”中设置外观为深色。
在 iOS 13 中,我们可以通过 UITraitCollection 来判断当前系统的外观模式。UIView 和 UIViewController 、UIScreen、UIWindow 都已经遵从了UITraitEnvironment这个协议,因此这些类都拥有一个叫做 traitCollection的属性,在这些类中,我们可以这样去判断当前 App 的外观模式:
BOOL isDark = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark);
另外,我们还可以通过 UITraitCollection.current这个属性来获取当前 App 的外观模式。但是并不是所有的时候获取的都是正确的,只有在下面这些方法中,才可以放心的使用这个属性:
- UIView:
draw(), layoutSubview(), traitCollectionDidChange(), tintColorDidChange()
- UIViewController:
viewWillLayoutSubviews(), viewDidLayoutSubviews(), traitCollectionDidChange()
- UIPresentationController:
containerViewWillLayoutSubviews(), containerViewDidLayoutSubviews(), traitCollectionDidChange()
如果应用不想适配暗黑模式,可以先暂时全局关闭暗黑模式: 在 Info.plist 文件中,添加 key 为 User Interface Style,类型为 String,value 设置为 Light即可。
或者直接修改info.plist源文件
UIUserInterfaceStyle
Light
在 iOS 13中,UIView、UIViewController 、UIWindow 有了一个 overrideUserInterfaceStyle的新属性,可以覆盖系统的外观模式。
单个页面或视图关闭暗黑模式,设置 overrideUserInterfaceStyle 为对应的模式,强制限制该视图与其子视图以设置的模式进行展示,不跟随系统模式改变进行改变。
self.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
如果你希望一个子视图监听系统的模式,请将 overrideUserInterfaceStyle 属性设置为UIUserInterfaceStyleUnspecified。
typedef NS_ENUM(NSInteger, UIUserInterfaceStyle) {
UIUserInterfaceStyleUnspecified,
UIUserInterfaceStyleLight,
UIUserInterfaceStyleDark,
} API_AVAILABLE(tvos(10.0)) API_AVAILABLE(ios(12.0)) API_UNAVAILABLE(watchos);
图片适配暗黑模式:
在Images.xcassets中点击图片,选择右边的Image Set,设置Appearances为“Any,Dark”,即可兼容暗黑模式,可以分别设置暗黑模式和正常模式的图片。
iOS 13 以下的系统会默认取Any状态下的设定,iOS 13 会根据系统外观模式取Any或Dark下的设定。