如何在Swift中处理深色模式的自定义颜色

fs_*_*gre 2 ios swift ios13 ios-darkmode

这是我目前UI Element Colors在深色模式下处理旧版本操作系统的方式。

extension UIColor {
    class var mySystemBackground: UIColor {
        if #available(iOS 13, *) {
            return .systemBackground
        } else {
            return .white
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,可以systemBackground知道它何时处于暗模式下以及何时处于亮模式下,并相应地进行了更改。我想使用自定义颜色做类似的事情。

例如,我有一个自定义的黄色,当前正在整个应用程序中使用,我想为处于深色模式的用户提供不同的颜色。

这是我在想的代码...

extension UIColor{
    class var mySystemYellowColor: UIColor {
        // default light-color 
        var myYellow = UIColor(red: 254/255, green: 219/255, blue: 2/255, alpha: 1.0) /* #fedb02 */

        if #available(iOS 13.0, *) {  

            if traitCollection.userInterfaceStyle == .light {
                return myYellow
            } else {
                // color for dark mode in iOS 13.0
                myYellow = UIColor(red: 242/255, green: 125/255, blue: 0/255, alpha: 1.0) /* #f27d00 */
            }
            return myYellow

        } else {
            return myYellow
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是在iOS13中处理深色模式的自定义颜色并回退其他操作系统的一种可行方法吗?

vad*_*ian 6

在资产目录中创建颜色。

资产目录中的颜色可以为不同的外观创建,并且可以使用UIColor(named:)API 进行访问

在界面中查看支持暗模式