如何将SwiftUI颜色更改为UIColor? [英] How can I change a SwiftUI Color to UIColor?
问题描述
尝试将SwiftUI颜色更改为UIColor的实例.
Trying to change a SwiftUI Color to an instance of UIColor.
我可以轻松地从UIColor中获取RGBA,但是我不知道如何获取"Color"实例以返回相应的RGB和不透明度值.
I can easily get the RGBA from the UIColor, but I don't know how to get the "Color" instance to return the corresponding RGB and opacity values.
@EnvironmentObject var colorStore: ColorStore
init() {
let red = //get red value from colorStore.primaryThemeColor
let green = //get red value from colorStore.primaryThemeColor
let blue = //get red value from colorStore.primaryThemeColor
let opacity = //get red value from colorStore.primaryThemeColor
let color = UIColor(red: red, green: green, blue: blue, alpha: opacity)
UINavigationBar.appearance().tintColor = color
}
...或者也许有更好的方法来完成我要寻找的东西.
...Or maybe there is a better way to accomplish what I am looking for.
推荐答案
该解决方案如何?
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)
}
}
用法:
let uiColor = myColor.uiColor()
这有点骇人听闻,但这至少是一件事情,直到我们得到一个有效的方法为止.这里的键是self.description
,它给出颜色的十六进制描述(如果不是动态的,我应该添加).剩下的只是获取颜色分量并创建UIColor
的计算.
It's a bit of a hack, but it's at least something until we get a valid method for this. The key here is self.description
which gives a hexadecimal description of the color (if it's not dynamic I should add). And the rest is just calculations to get the color components, and create a UIColor
.
这篇关于如何将SwiftUI颜色更改为UIColor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!