【发布时间】:2019-11-14 09:08:06
【问题描述】:
在 UIKit 中,我们可以使用扩展来为几乎所有东西设置十六进制颜色。 https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-hex-color-to-a-uicolor
但是当我尝试在 SwiftUI 上执行此操作时,这是不可能的,看起来 SwiftUI 没有将 UIColor 作为参数。
Text(text)
.color(UIColor.init(hex: "FFF"))
错误信息:
Cannot convert value of type 'UIColor' to expected argument type 'Color?'
我什至尝试为Color 扩展,而不是UIColor,但我没有任何运气
我的颜色扩展:
导入 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
)
}
}
错误信息:
Incorrect argument labels in call (have 'red:green:blue:alpha:', expected '_:red:green:blue:opacity:')
【问题讨论】:
-
初始化是这个:developer.apple.com/documentation/swiftui/color/3265484-init 它缺少一个参数,正如您在错误消息中看到的那样:
'red:green:blue:alpha:'vs'_:red:green:blue:opacity:,请参阅开头的_:对于_ colorSpace:和opacity与alpha。 -
@Larme 是的,我试过了,它修复了编译错误,但没有任何结果,它没有为视图设置颜色,你自己解决了吗?如果你这样做,请添加代码。