in UIKit we could use an Extension to set hex color to almost everything. https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor
but when I'm trying to do it on SwiftUI, it's not possible, it looks like the SwiftUI does not get the UIColor as parameter.
Text(text)
.color(UIColor.init(hex: "FFF"))
error message:
Cannot convert value of type 'UIColor' to expected argument type 'Color?'
I even tried to make an extension for Color
, instead of UIColor
, but I haven't any luck
my extension for Color:
import SwiftUI
extension Color {
init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 0
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let r = (rgbValue & 0xff0000) >> 16
let g = (rgbValue & 0xff00) >> 8
let b = rgbValue & 0xff
self.init(
red: CGFloat(r) / 0xff,
green: CGFloat(g) / 0xff,
blue: CGFloat(b) / 0xff, alpha: 1
)
}
}
error message:
Incorrect argument labels in call (have 'red:green:blue:alpha:', expected '_:red:green:blue:opacity:')
'red:green:blue:alpha:'
vs'_:red:green:blue:opacity:
, see the_:
at the start which is for the_ colorSpace:
andopacity
vsalpha
. – Larme