Evaluating UITraitCollection's hasDifferentColorAppearance(comparedTo:) result

[亡魂溺海] 提交于 2019-12-11 03:35:45

问题


In my app I need to make some custom UI changes when iOS system dark mode settings change. According to https://developer.apple.com/videos/play/wwdc2019/214/ it's explicitly mentioned to implement traitCollectionDidChange and compare the previous and current trait collection using hasDifferentColorAppearance(comparedTo:).

Documentation says:

Use this method to determine whether changing the traits of the current environment would also change the colors in your interface. For example, changing the userInterfaceStyle or accessibilityContrast property usually changes the colors of your interface.

In my view controller's subclass I implemented

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {

        super.traitCollectionDidChange(previousTraitCollection)

        if #available(iOS 13.0, *),
            self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {

            let isSameUserInterfaceStyle = (self.traitCollection.userInterfaceStyle == previousTraitCollection?.userInterfaceStyle)
            let isSameAcessibilityContrast = (self.traitCollection.accessibilityContrast == previousTraitCollection?.accessibilityContrast)

            // do custom stuff
        }
    }

But in some cases both isSameUserInterfaceStyle and isSameAcessibilityContrast evaluate to true which I did not expect if hasDifferentColorAppearance(comparedTo:) also returns true. I'm not a fan of working around Apple's suggested API usage but on the other hand I don't want to make unnecessary changes to my UI if userInterfaceStyle did not actually change. So I'm not sure if I should rely on the result of hasDifferentColorAppearance(comparedTo:) or if it suffices to just compare userInterfaceStyle of both trait collections.


回答1:


A deeper investigation of both trait collections brought to light that the current trait collection's userInterfaceLevel property was set .elevated. All other properties were identical. The change in userInterfaceLevel's value was caused by presenting another view controller as a popover. Considering this fact I need to additionally check for self.traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle to determine whether the dark / light appearance has actually changed.



来源:https://stackoverflow.com/questions/57993277/evaluating-uitraitcollections-hasdifferentcolorappearancecomparedto-result

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