您快到了,您使用了错误的初始化参数:
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: Double(r) / 0xff, green: Double(g) / 0xff, blue: Double(b) / 0xff)
}
}
Another alternative below that uses Int for hex but of course, it can be changed to String if you prefer that.
extension Color { init(hex: Int, alpha: Double = 1) { let compOnents= ( R: Double((hex >> 16) & 0xff) / 255, G: Double((hex >> 08) & 0xff) / 255, B: Double((hex >> 00) & 0xff) / 255 ) self.init( .sRGB, red: components.R, green: components.G, blue: components.B, opacity: alpha ) } }
Usage examples:
Color(hex: 0x000000) Color(hex: 0x000000, alpha: 0.2)