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

1

6

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?

Cudlip answered 12/8, 2020 at 8:21 Comment(0)
H
12

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.

Helman answered 12/8, 2020 at 8:36 Comment(2)
This makes sense. Is this described in the documentation?Cudlip
Not that I know of. I remember seeing a tweet or something about it when iOS 13 came out. You can observe it by swiping up to get the task switcher then swiping down to get the control centre and switching between light & dark. You can see all of the snapshots updateHelman

© 2022 - 2024 — McMap. All rights reserved.