简体   繁体   English

iOS 13 黑暗模式:traitCollectionDidChange 仅在第一次调用

[英]iOS 13 Dark mode: traitCollectionDidChange only called the first time

My app uses custom color themes but iOS13 users can opt into following dark mode.我的应用程序使用自定义颜色主题,但 iOS13 用户可以选择进入以下深色模式。

I thought I could simply update my colors in the ViewController's traitCollectionDidChange() but for some reason, this function is only called the first time the user changes the interface style in the iOS settings.我以为我可以简单地在ViewController's traitCollectionDidChange()中更新我的 colors 但出于某种原因,这个 function 仅在用户第一次更改 iOS 设置中的界面样式时被调用。 While this may be sufficient for most users, ideally traitCollectionDidChange() should be called every time the user changes their iOS settings.虽然这对大多数用户来说可能就足够了,但理想情况下,每次用户更改其 iOS 设置时都应调用traitCollectionDidChange()

Just very basic:只是非常基本的:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  super.traitCollectionDidChange(previousTraitCollection)
  print(#function)

  guard traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle else { return }

  NotificationCenter.default.post(name: NSNotification.Name(Keys.Notifications.updateColorTheme), object: nil)
}

I launch my app, leave it, change appearance in the iOS settings: the next time I open the app (open, not launch), the above function is called and the app updates colors. Now, when I repeat the same process, the function is not called anymore.我启动我的应用程序,离开它,更改 iOS 设置中的外观:下次我打开应用程序(打开,而不是启动)时,将调用上面的 function 并且应用程序更新 colors。现在,当我重复相同的过程时,不再调用 function。

I found that if I set UIViewController's overrideUserInterfaceStyle property, then the traitCollectionDidChange method not called, however when I don't set this overrideUserInterfaceStyle property, the traitCollectionDidChange is called.我发现如果我设置 UIViewController 的overrideUserInterfaceStyle属性,则不会调用traitCollectionDidChange方法,但是当我不设置此overrideUserInterfaceStyle属性时,会调用traitCollectionDidChange

maybe there have some internal method call judge in UIKit based on overrideUserInterfaceStyle property.可能在 UIKit 中有一些基于overrideUserInterfaceStyle属性的内部方法调用判断。

Hope this help.希望这有帮助。

The default value of overrideUserInterfaceStyle is .unspecified . overrideUserInterfaceStyle的默认值为.unspecified If you want to be called it again, just revert it to .unspecified after setting to .light or `.dark'如果你想再次调用它,只需在设置为.light或 `.dark' 后将其恢复为.unspecified

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM