获取 UIColor 的深色风格

אור*_*hpt 7 uikit uicolor ios swift

我有这个UIColor

左边的颜色光外观上显示的

深色外观显示正确的颜色


我希望能够在设备处于浅色外观时获得正确的颜色

并能够在设备处于深色外观时获得左侧颜色


我知道我可以复制它并创建另一种颜色,然后使用该颜色,但是有没有办法UIColor从代码中获取变量的所有变化?谢谢

Leo*_*bus 14

您可以使用 UIColor 方法func resolvedColor(with traitCollection: UITraitCollection) -> UIColor并选择所需的特征集合:

extension UIColor {
    var dark: UIColor  { resolvedColor(with: .init(userInterfaceStyle: .dark))  }
    var light: UIColor { resolvedColor(with: .init(userInterfaceStyle: .light)) }
}
Run Code Online (Sandbox Code Playgroud)

例子

let systemPurple = UIColor.systemPurple   // r 0,686 g 0,322 b 0,871 a 1,0
systemPurple.dark                         // r 0,749 g 0,353 b 0,949 a 1,0
systemPurple.light                        // r 0,686 g 0,322 b 0,871 a 1,0
Run Code Online (Sandbox Code Playgroud)