Search code examples
iosswiftios-darkmodeuitraitcollection

iOS dark mode. User Interface Style changes back and forth on entering on the background


I support dark mode. In some of my view controllers I use traitCollectionDidChange(_) for handling user interface style changes.

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        if #available(iOS 13.0, *) {
            if let p = previousTraitCollection {
                print("TRAIT COLLECTION \(p.userInterfaceStyle.desc) -> \(traitCollection.userInterfaceStyle.desc). \(UIApplication.shared.applicationState.desc); \(p.hasDifferentColorAppearance(comparedTo: traitCollection) ? "TRAIT CHANGED" : "TRAIT SAME")")
            }
        }
    }

When I press the home button and go on the background, this method firing twice:

TRAIT COLLECTION DARK -> LIGHT. BACKGROUND; TRAIT CHANGED
TRAIT COLLECTION LIGHT -> DARK. BACKGROUND; TRAIT CHANGED

And when I change appearance in iOS settings and back to the foreground, I get

TRAIT COLLECTION DARK -> LIGHT. INACTIVE; TRAIT CHANGED

Strange. And every time I go on the background, I get user interface style changes back and forth. Why?


Solution

  • This is expected behaviour. When your app is suspended, iOS takes a screen snapshot for display in the app switcher.

    To allow for the case where a switch from light to dark or dark to light occurs while your app is suspended, it actually takes two snapshots; one light and one dark.

    iOS can then display the correct snapshot in the app switcher.