我正在尝试在多场景应用程序中实现 ios13 暗模式。
不幸的是,当我关闭一个将其拖过屏幕边缘的场景时,traitCollectionDidChange 方法会被多次调用,并且总是使用不同的值,导致我的 UI 在暗模式和亮模式之间闪烁。
怎么了?
这是我的实现
func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
print("THEME instance: \(self)")
let currentTraitCollection = self.traitCollection
var hasUserInterfaceStyleChanged = false
hasUserInterfaceStyleChanged = previousTraitCollection.hasDifferentColorAppearanceCompared(to: currentTraitCollection)
print("THEME hasUserInterfaceStyleChanged = \(hasUserInterfaceStyleChanged ? "YES" : "NO")")
if hasUserInterfaceStyleChanged {
let userInterfaceStyle = currentTraitCollection.userInterfaceStyle // Either .unspecified, .light, or .dark
switch userInterfaceStyle {
case .unspecified:
print("THEME UIUserInterfaceStyleUnspecified")
case .light:
print("THEME UIUserInterfaceStyleLight")
case .dark:
print("THEME UIUserInterfaceStyleDark")
}
} else {
print("THEME NOT CHANGED")
}
}
这是控制台中记录的语句
当新场景出现时...
THEME instance: <MainControllerViewController: 0x117e55910>
THEME hasUserInterfaceStyleChanged = YES
THEME UIUserInterfaceStyleLight
当添加的场景消失时......
THEME instance: <MainControllerViewController: 0x117e55910>
THEME hasUserInterfaceStyleChanged = YES
THEME UIUserInterfaceStyleDark
THEME instance: <MainControllerViewController: 0x117e55910>
THEME hasUserInterfaceStyleChanged = YES
THEME UIUserInterfaceStyleLight
THEME instance: <MainControllerViewController: 0x117e55910>
THEME hasUserInterfaceStyleChanged = NO
THEME NOT CHANGED
THEME instance: <MainControllerViewController: 0x117e55910>
THEME hasUserInterfaceStyleChanged = YES
THEME UIUserInterfaceStyleDark
THEME instance: <MainControllerViewController: 0x117e55910>
THEME hasUserInterfaceStyleChanged = YES
THEME UIUserInterfaceStyleLight
与此同时,我没有更改为暗模式(总是亮)......所以我希望只是主题没有改变。