How to convert UIColor to SwiftUI‘s Color
I want to use a UIColor as foregroundcolor for an object but I don’t know how to convert UIColor to a Color
var myColor: UIColor
RoundedRectangle(cornerRadius: 5).foregroundColor(UIColor(myColor))
Starting with beta 5, you can create a Color from a UIColor:
Color(UIColor.systemBlue)
Both iOS and macOS
Color
has a native initializer for it that takes an UIColor
or NSColor
as an argument:
Color(.red) /* or any other UIColor/NSColor you need INSIDE parentheses */
DO NOT call Color(UIColor.red)
explicitly !!!. This will couple your SwiftUI code to the UIKit
. Instead, just call Color(.red)
That will infer the correct module automatically.
Also, Note this difference:
Color.red /* this `red` is SwiftUI native `red` */
Color(.red) /* this `red` is UIKit `red` */
Note that:
Color.red
and UIColor.red
are NOT same! They have different values and look different with each other. So DON'T assume this worth nothing
These are equal instead: SwiftUI.Color.Red == UIKit.UIColor.systemRed
Also, You can check out How to get RGB components from SwiftUI.Color
Extension
You can implement a custom variable for it to make it more like cgColor
and ciColor
extension UIColor {
/// The SwiftUI color associated with the receiver.
var suColor: Color { Color(self) }
}
so it would be like:
UIColor.red // UIKit color
UIColor.red.suColor // SwiftUI color
UIColor.red.cgColor // Core graphic color
UIColor.red.ciColor // Core image color
Note: Click here to see How to convert SwiftUI.Color
to UIColor