Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change a SwiftUI Color to UIColor?

Tags:

macos

ios

swiftui

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?

like image 421
Gavin Jensen Avatar asked Jul 29 '19 16:07

Gavin Jensen


People also ask

How do I change the RGB color in Swift?

In Objective-C, we use this code to set RGB color codes for views: #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] view.

How do you convert Heicolor to hex?

To convert a UIColor instance to a hex value, we define a convenience method, toHex(alpha:) . The method accepts one parameter of type Bool , which indicates whether the alpha value should be included in the string that is returned from the method.


1 Answers

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

like image 130
Mojtaba Hosseini Avatar answered Sep 22 '22 09:09

Mojtaba Hosseini