Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check ios device's current userInterfaceStyle programmatically?

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.

like image 309
Raushan Kumar Avatar asked Aug 29 '19 07:08

Raushan Kumar


2 Answers

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
}
like image 157
Hammerhead Avatar answered Oct 27 '22 05:10

Hammerhead


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.
    }
}
like image 43
Alexander W Avatar answered Oct 27 '22 04:10

Alexander W