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

那年仲夏 提交于 2019-12-30 05:20:05

问题


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.


回答1:


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
}



回答2:


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.
    }
}


来源:https://stackoverflow.com/questions/57704885/how-can-i-check-ios-devices-current-userinterfacestyle-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!