Avoid calls to traitCollectionDidChange when minimising app

Viewed 256

I have a bug in my app. The cause of this bug is the fact that the UIViewController updates a UITableView cell after the UI theme is changed from light to dark or vice versa.

I can fix this bug, the bug itself is not a problem.

However, I have noticed some weird behaviour. When I minimise my app, both

func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)

and

func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)

get called twice. I have not changed the UI theme, but when I add the following code to my UIViewController

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
{
    super.willTransition(to: newCollection, with: coordinator)

    Swift.print("Changing to", newCollection.userInterfaceStyle == .dark ? "dark" : "light", "mode.")
}

I get the following output:

Changing to dark mode.
Changing to light mode.

Like I said, all I did was minimising my app (pressing the Home button). When actually changing the UI theme, it will only get called once, which is fine.

I will check the actual state before reloading my UITableView (i.e. only reload it when the app state is inactive, which is the state when using the Notification Center to change the UI theme), but I am just curious. This seems like a bug to me.

Why is the delegate triggered twice when minimising the app?

1 Answers

This is done on purpose. As you might know iOS takes a screenshot before exiting an app to be displayed when going trough the App Switcher (Multitasking). Since iOS 13 it takes a screenshot in both dark light mode, and thus changes the trait collection very briefly. This is done so that when the user switches between light and dark mode, the screenshots in the app switcher will also update (you can check it out). You should optimize your app to accommodate for this behavior.

Related