How can I change a SwiftUI Color to UIColor?
I'm trying to change a SwiftUI Color to an instance of UIColor.
I can easily get the RGBA from the UIColor, but I don't know how to get the "Color" instance to return the corresponding RGB and opacity values.
@EnvironmentObject var colorStore: ColorStore
init() {
let red = //get red value from colorStore.primaryThemeColor
let green = //get green value from colorStore.primaryThemeColor
let blue = //get blue value from colorStore.primaryThemeColor
let alpha = //get alpha value from colorStore.primaryThemeColor
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
UINavigationBar.appearance().tintColor = color
}
...or maybe there is a better way to accomplish what I am looking for?
SwiftUI 2.0
There is a new initializer that takes a Color
and returns a UIColor
for iOS or NSColor
for macOS now. So:
iOS
UIColor(Color.red)
macOS
NSColor(Color.red)
Core Graphics
UIColor(Color.red).cgColor /* For iOS */
NSColor(Color.red).cgColor /* For macOS */
If you are looking for color components, you can find a helpful extensions here in this answer
Also, check out How to convert UIColor to SwiftUI‘s Color
How about this solution?
extension Color {
func uiColor() -> UIColor {
if #available(iOS 14.0, *) {
return UIColor(self)
}
let components = self.components()
return UIColor(red: components.r, green: components.g, blue: components.b, alpha: components.a)
}
private func components() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
let scanner = Scanner(string: self.description.trimmingCharacters(in: CharacterSet.alphanumerics.inverted))
var hexNumber: UInt64 = 0
var r: CGFloat = 0.0, g: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0
let result = scanner.scanHexInt64(&hexNumber)
if result {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
}
return (r, g, b, a)
}
}
Usage:
let uiColor = myColor.uiColor()
It's a bit of a hack, but it's at least something until we get a valid method for this. The key here is self.description
which gives a hexadecimal description of the color (if it's not dynamic I should add). And the rest is just calculations to get the color components, and create a UIColor
.