AvisSiva AvisSiva - 4 months ago 40
Swift Question

Can't Convert UIColor from hex colour string in Swift?

I am using this code for create UIColor from hex value. Its working perfectly.

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)
}
}


Usage:

var textColor = UIColor(netHex: 0xffffff)


This code works perfectly for Int hex code. But It needs hex code 0xffffff as Int type. I am having the hex code from web service. It will be like "#ffffff" (String not Int). I can convert this string like "0xffffff". But I can't convert from "0xffffff"(String) to 0xffffff (Int).

I need something like this

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


or better like this:

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


Thanks in advance.

Answer

update: Xcode 7.1 • Swift 2.1

extension UIColor {
    convenience init(string: String) {
        var chars = string.hasPrefix("#") ? Array(string.characters.dropFirst()) : Array(string.characters)
        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 1
        switch chars.count {
        case 3:
            chars = [chars[0], chars[0], chars[1], chars[1], chars[2], chars[2]]
            fallthrough
        case 6:
            chars = ["F","F"] + chars
            fallthrough
        case 8:
            a = CGFloat(Float(strtoul(String(chars[0...1]), nil, 16)) / 255)
            r = CGFloat(Float(strtoul(String(chars[2...3]), nil, 16)) / 255)
            g = CGFloat(Float(strtoul(String(chars[4...5]), nil, 16)) / 255)
            b = CGFloat(Float(strtoul(String(chars[6...7]), nil, 16)) / 255)
        default:
            a = 0
        }
        self.init(red: r, green: g, blue:  b, alpha: a)
    }
}

var textColor =  UIColor(string: "00F")       // r 0.0 g 0.0 b 1.0 a 1.0

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