I am able to get userInterfaceStyle using TraitCollection of any view or ViewController ie. Dark or Light. But when I forced app to use Dark or light Mode, then I want to know what is the current userInterfaceStyle of iOS device irrespective of app?
I tried Traitcollection of UIScreen but still its provide userInterfaceStyle of app not device.
Try UIScreen.main
, swift 5 example:
// OS-wide theme available on iOS 13.
@available(iOS 13.0, *)
var osTheme: UIUserInterfaceStyle {
return UIScreen.main.traitCollection.userInterfaceStyle
}
In the cases where you have multiple ViewControllers or Windows where you want the interface style to be dynamic (or as in your case, locked), I would argue to use the traitCollectionDidChange(_:) callback and look at the property userInterfaceStyle
. This will reflect the current state of the interface style (even if locked). Just remember that child view controllers will inherit their parent´s setting.
This way you can design your code to behave correctly depending on the current interface style being transitioned from->to. The below example will work in custom UIViewControllers as well as custom UIViews.
Example (swift 4):
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if self.traitCollection.userInterfaceStyle != previousTraitCollection.userInterfaceStyle {
// Your custom implementation here that is run right after the userInterfaceStyle has changed.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With