我对 Swift 有点陌生,遇到了一个无法解决的问题。 我有一个字符串,其值表示十六进制,例如“#004080”。这个值直接来自数据库,我想用它来修改UIlabel的颜色,但我做不到。
这是我的摘要代码:
...
let color1 = "004080"
...
//try do this:
plato1.textColor = UIColor(hex: color1)
//Error:
// Cannot convert value of type 'String' to expected argument type 'Int'
//Try this too:
plato1.textColor = UIColor(hex: Int(Color1)!)
//Error:
//This returns a different color: 4080, not 004080
//EXTENSION FOR A HEXADECIMAL
extension UIColor {
convenience init(hex: Int) {
let components = (
R: CGFloat((hex >> 16) & 0xff) / 255,
G: CGFloat((hex >> 08) & 0xff) / 255,
B: CGFloat((hex >> 00) & 0xff) / 255
)
self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
}
}
对我来说,用 swift 来表示十六进制有点困惑。
有什么建议吗?
谢谢你!
最佳答案
您可以将字符串拆分为两个字符的字符串,分别代表 RGB。这将解决不显示前导零的问题。
关于Swift 3 在文本颜色中使用十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54550132/