Swift 3 在文本颜色中使用十六进制

标签 swift swift3 hex textcolor

我对 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/

相关文章:

使用十六进制值创建字符数组

将整数值转换为十六进制字符串

Java生成代码字节256*256 & 0xff

ios - 如何快速从文件路径中获取文件名

string - SWIFT: "Compressed"/小字符串类型?每个字符 1 个字节?

objective-c - 我的 swift 函数的返回类型必须继承自 NSObject

ios - 如何在定时器选择器上传递参数

ios - 使用 SwifyStoreKit 在应用内购买无法获取有关产品的信息

ios - 在 Swift 3 iPhone 应用程序中使用套接字

ios - Alamofire 不同请求的不同超时