Swift: If traitCollection.userInterfaceStyle == .unspecified, how do I determine if it's in light or dark mode?
Asked Answered
M

1

6

In the settings of my app, the user can choose between 3 system themes: light, dark, or default (which matches the phone's theme).

I do this by finding the keyWindow and setting overrideUserInterfaceStyle = .dark for dark mode, overrideUserInterfaceStyle = .light for light mode, and overrideUserInterfaceStyle = .unspecified for default.

The problem I'm having is I'm using MapBox within my app and I have both a darkStyleURL and a lightStyleURL. When the user chooses a theme I update the style url as follows:

self.styleURL = self.traitCollection.userInterfaceStyle == .dark ? URL(string: darkStyleURL) : URL(string: lightStyleURL)

But the problem with doing it this way is if the user chooses default as the theme, the traitCollection.userInterfaceStyle is going to be equal to .unspecified. So when the code above triggers, it'll use the lightStyleURL EVEN IF the user's device is in dark mode.

So my question is, after setting overrideUserInterfaceStyle = .unspecified is there another way to determine the user's device theme?

Or is there a better way of handling the use case of matching the device theme or switching between all three options? Any help will be greatly appreciated. Thanks!

Mchail answered 23/7, 2021 at 21:55 Comment(3)
Why not just follow the device theme? Is it really worth adding complexity to your app for a feature that users will probably never use?Orthohydrogen
UITraitCollection.current.userInterfaceStyleDoodlesack
@Orthohydrogen that wasn’t really an answer to the question. Thanks and not up to me. Dudnyk I’ll try this out when I get back monday thanks for the suggestion!Mchail
P
9

You can use UIScreen.main.traitCollection.userInterfaceStyle to get the current device theme independent of the overridden appearance on the window.

Posse answered 24/7, 2021 at 19:36 Comment(2)
Marking this as "correct" although I am using Eugene Dudnyks answer of UITraitCollection.current.userInterfaceStyle instead. But it's close enough I believe both work. Thanks for the help!Mchail
In iOS18 UITraitCollection.current.userInterfaceStyle no longer works. Only UIScreen.main.traitCollection.userInterfaceStyle gives you the true system appearance. UITraitCollection.current.userInterfaceStyle gives you the appearance of your app/window.Donella

© 2022 - 2024 — McMap. All rights reserved.