如何在Swift中创建十六进制颜色字符串UIColor初始化程序?

时间:2015-08-03 08:06:35

标签: ios swift nsstring int uicolor

我正在使用此代码从十六进制值创建UIColor。它工作得很好。

extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
   assert(red >= 0 && red <= 255, "Invalid red component")
   assert(green >= 0 && green <= 255, "Invalid green component")
   assert(blue >= 0 && blue <= 255, "Invalid blue component")

   self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}

convenience init(netHex:Int) {
   self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}

用法:

var textColor = UIColor(netHex: 0xffffff)

此代码适用于Int十六进制代码。但它需要十六进制代码0xffffff作为Int类型。我有来自Web服务的十六进制代码。它将像“#ffffff”(String not Int)。我可以将此字符串转换为“0xffffff”。但我无法从“0xffffff”(字符串)转换为0xffffff(Int)。

我需要这样的东西

var textColor = UIColor(netHex: "0xffffff")

或者更好:

var textColor = UIColor(netHex: "#ffffff")

提前致谢。

1 个答案:

答案 0 :(得分:17)

Xcode 9•Swift 4或更高版本(适用于Swift 3或更早版本检查编辑历史记录)

extension UIColor {
    convenience init?(hexString: String) {
        var chars = Array(hexString.hasPrefix("#") ? hexString.dropFirst() : hexString[...])
        let red, green, blue, alpha: CGFloat
        switch chars.count {
        case 3:
            chars = chars.flatMap { [$0, $0] }
            fallthrough
        case 6:
            chars = ["F","F"] + chars
            fallthrough
        case 8:
            alpha = CGFloat(strtoul(String(chars[0...1]), nil, 16)) / 255
            red   = CGFloat(strtoul(String(chars[2...3]), nil, 16)) / 255
            green = CGFloat(strtoul(String(chars[4...5]), nil, 16)) / 255
            blue  = CGFloat(strtoul(String(chars[6...7]), nil, 16)) / 255
        default:
            return nil
        }
        self.init(red: red, green: green, blue:  blue, alpha: alpha)
    }
}
if let textColor = UIColor(hexString: "00F") {
    print(textColor) // r 0.0 g 0.0 b 1.0 a 1.0
}     

UIColor(hexString: "#00F")      // r 0.0 g 0.0 b 1.0 a 1.0
UIColor(hexString: "#0000FF")   // r 0.0 g 0.0 b 1.0 a 1.0
UIColor(hexString: "#FF0000FF") // r 0.0 g 0.0 b 1.0 a 1.0