问题描述
在我的应用中,当iOS系统暗模式设置更改时,我需要进行一些自定义UI更改.根据 https://developer.apple.com/videos/play/wwdc2019/214/明确提到要实现traitCollectionDidChange
并使用hasDifferentColorAppearance(comparedTo:)
比较以前和当前的特征集.
In my app I need to make some custom UI changes when iOS system dark mode settings change. According to https://developer.apple.com/videos/play/wwdc2019/214/ it's explicitly mentioned to implement traitCollectionDidChange
and compare the previous and current trait collection using hasDifferentColorAppearance(comparedTo:)
.
文档说:
我在视图控制器的子类中实现了
In my view controller's subclass I implemented
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *),
self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
let isSameUserInterfaceStyle = (self.traitCollection.userInterfaceStyle == previousTraitCollection?.userInterfaceStyle)
let isSameAcessibilityContrast = (self.traitCollection.accessibilityContrast == previousTraitCollection?.accessibilityContrast)
// do custom stuff
}
}
但是在某些情况下,isSameUserInterfaceStyle
和isSameAcessibilityContrast
都将评估为true
,如果hasDifferentColorAppearance(comparedTo:)
也返回true
,我没想到.我不喜欢解决Apple建议的API使用问题,但另一方面,如果userInterfaceStyle
实际没有更改,我不想对UI进行不必要的更改.因此,我不确定是否应该依靠hasDifferentColorAppearance(comparedTo:)
的结果还是仅比较两个特征集的userInterfaceStyle
就足够了.
But in some cases both isSameUserInterfaceStyle
and isSameAcessibilityContrast
evaluate to true
which I did not expect if hasDifferentColorAppearance(comparedTo:)
also returns true
.I'm not a fan of working around Apple's suggested API usage but on the other hand I don't want to make unnecessary changes to my UI if userInterfaceStyle
did not actually change. So I'm not sure if I should rely on the result of hasDifferentColorAppearance(comparedTo:)
or if it suffices to just compare userInterfaceStyle
of both trait collections.
推荐答案
对两个特征集的更深入研究表明,当前特征集的userInterfaceLevel
属性设置为.elevated
.其他所有属性均相同. userInterfaceLevel
值的更改是由于将另一个视图控制器显示为弹出框而引起的.考虑到这一事实,我需要另外检查self.traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle
以确定暗/亮外观是否确实发生了变化.
A deeper investigation of both trait collections brought to light that the current trait collection's userInterfaceLevel
property was set .elevated
. All other properties were identical. The change in userInterfaceLevel
's value was caused by presenting another view controller as a popover. Considering this fact I need to additionally check for self.traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle
to determine whether the dark / light appearance has actually changed.
这篇关于评估UITraitCollection的hasDifferentColorAppearance(comparedTo :)结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!