I want to convert SwiftUI view Color to UIKit UIcolor component. I have tried several ways and also refer the StackOverflow already given answers, But they did not work. It was also mentioned by some users in those posts. I have gone through the below code which is proposed by turingtested
but this is not working. Any suggestions or help is really appreciated.
fileprivate extension Color {
func uiColor() -> UIColor {
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)
}
}
If you are looking for an up-to-date answer:
From iOS 14 onward, the UIColor
class has an initializer, which takes a SwiftUI color as argument: UIColor(Color.red)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With