How can I detect when the system changes dark/light mode in Swift?

445 Views Asked by At

I know there are plenty of answers pointing to traitCollectionDidChange, but that is going to be called when the userInterfaceStyle of a view controller changes, and I would like to let the user select between System, Light and Dark mode, so I am overriding the userInterfaceStyle of my view controllers and going to the device's settings and turning dark/light mode on won't call traitCollectionDidChange. Is there some other way to handle this? Am I going about it wrong?

When the app starts I can check UIScreen.main.traitCollection.userInterfaceStyle, so if there would be some way to observe changes to this property or use a notification, that would do it. But again, maybe I'm approaching this wrong, so I would appreciate any suggestions.

1

There are 1 best solutions below

1
On

You can actually use the following method, e.g. in your UIViewController to observe changes regarding the theme.

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