Search code examples
swiftios-darkmode

traitCollectionDidChange is not called for dark mode


I'm implementing dark mode in my app, in a viewDidLoad. I added:

switch self.traitCollection.userInterfaceStyle {
case .dark:
    overrideUserInterfaceStyle = .dark
case .light:
    overrideUserInterfaceStyle = .light
case .unspecified:
    overrideUserInterfaceStyle = .light
@unknown default:
    overrideUserInterfaceStyle = .light
}

And it works perfectly fine, but I want to set when the theme is changed on the device when the app is open, it automatically change the theme. So I added traitCollectionDidChange to the view controller

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
  
    switch self.traitCollection.userInterfaceStyle {
    case .dark:
        overrideUserInterfaceStyle = .dark
    case .light:
        overrideUserInterfaceStyle = .light
    case .unspecified:
        overrideUserInterfaceStyle = .light
    @unknown default:
        overrideUserInterfaceStyle = .light
    }
}

But it's never called, should I do anything more?

Thanks for your help in advance.


Solution

  • You dont need to change it for yourself. If you use system colors, the change will be automatic (if you don't override the default user interface style). Delete this code, and set your colors to systemColors.