hasDifferentColorAppearance is true when app is backgrounded
Asked Answered
T

1

8

Apple recommends that we use traitCollectionDidChange and compare trait collections using hasDifferentColorAppearance to catch when dark mode is toggled, and act on it if we need to. Like this:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)
    if #available(iOS 13.0, *) {
        let hasUserInterfaceStyleChanged = previousTraitCollection?.hasDifferentColorAppearance(comparedTo: traitCollection) ?? false
        if (hasUserInterfaceStyleChanged) {
            //Update UI
        }
    }
}

I use this to update the UI, clear some caches etc when switching between dark and light mode.

For some reason traitCollectionDidChange fires and hasDifferentColorAppearance evaluates to true every time my app is backgrounded, no matter if I have dark mode enabled on the device or not. It seems the previousTraitCollection and the current traitCollection never have matching interfaceStyles in this case. I would rather avoid doing the updates I do when the userInterfaceStyle changes if the userInterfaceStyle hasn't actually changed.

Is this a bug, or am I just missing something?

Trichromatic answered 22/9, 2019 at 18:44 Comment(2)
Have you verified whether the interfaceStyles are actually different or not? hasDifferentColorAppearance can return true even when the interfaceStyles are the same. It's other traits that may be different.Doubletongued
@Doubletongued Yes, they are different. When dark mode is off on my phone the previous interfaceStyle is light, and the current one dark. But traitCollectionDidChange is actually called twice everytime the app is backgrounded. The first time, the previous interfaceStyle is light and the current dark, the second time the previous is dark and the current one light. So it's as if it goes from light to dark and then back to light again.Trichromatic
S
9

iOS is creating snapshots of your UI for light and dark appearance (and also for portrait and landscape orientation) every time the app is backgrounded for previewing your app in the app switcher UI. So this is perfectly normal behavior.

Size answered 22/9, 2019 at 19:24 Comment(1)
I really wish this is mention in the documentation. Every time I hit an issue caused by this behaviour I spend around 30 mins wondering why its happening and then coming back to this thread :)Vaccination

© 2022 - 2024 — McMap. All rights reserved.