I'm trying to convert a Color to UIColor. Unfortunately, when the SwiftUI color is dynamic (different value for light & dark) the UIColor created is not.
Here is some code example to illustrate the issue:
let lightTraits = UITraitCollection(userInterfaceStyle: .light)
let darkTraits = UITraitCollection(userInterfaceStyle: .dark)
let uiColor = UIColor(dynamicProvider: {
$0.userInterfaceStyle == .dark ? .red : .yellow
})
uiColor.resolvedColor(with: lightTraits).hexadecimalRepresentation // #FFFF00 (== .yellow: OK)
uiColor.resolvedColor(with: darkTraits).hexadecimalRepresentation // #FF0000 (== .red: OK)
let color = Color(uiColor: uiColor)
let invalidColor = UIColor(color)
invalidColor.resolvedColor(with: lightTraits).hexadecimalRepresentation // #FFFF00 ( == .yellow: OK)
invalidColor.resolvedColor(with: darkTraits).hexadecimalRepresentation // #FFFF00 (.yellow ??)
extension UIColor {
var hexadecimalRepresentation: String? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
return String(format: "#%02lX%02lX%02lX", lroundf(Float(r) * 255), lroundf(Float(g) * 255), lroundf(Float(b) * 255))
}
}
I believe UIColor(_ color: Color) is only reading the color for one color scheme...