How can I change a SwiftUI Color to UIColor?

Gavin Jensen picture Gavin Jensen · Jul 29, 2019 · Viewed 10.8k times · Source

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?

Answer

Mojtaba Hosseini picture Mojtaba Hosseini · Jul 20, 2020

iOS 14 / macOS 10.16

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 my helpful extensions here in this answer