Search code examples
swiftuikitswiftui

How to use SwiftUI Color in UIKit View


I am using the iOS Charts library wrapped in UIViewRepresentable to use a line chart within a SwiftUI project. I need to set some colors on the chart in UIColor that match the system colors that I have used in the rest of the SwiftUI project. I assumed that UIColor.red, for example, would be the same as Color.red in swiftUI, however this is not the case with any of the default system colors. They all are slightly different than each other. How can I bridge these two views and use the SwiftUI colors I have used in the wrapped UIView?

I've seen that there is a way to initialize a SwiftUI Color from a UIColor using

Color(UIColor.red)

but have found no equivalent to go the other way. Here's a example of the differences in the colors.

UIColor enter image description here

Color enter image description here


Solution

  • With support for dark mode in iOS 13, the UIColors have been updated: .red has been replaced by .systemRed which has slightly different tones of red to allow it to support light and dark modes. This will be equivalent to SwiftUI's .red.