Swift3 写UIColor的十六进制颜色扩展—UIColor+ColorHexString

在开发中通常UI工程师给我们的设计图上的标注都是十六进制的,但是在iOS的官方Api中并没有提供给我们提供这样一个方法入口,在OC中遇到这个问题我们会使用一个优秀的扩展UIColor+ColorHexString,但是apple开发语言的趋势在向Swift方向发展已经是不可辨的了,于是根据UIColor+ColorHexString用Swift3重写了一个扩展,记在这里.

使用的方法跟之前一样

btn.setTitleColor(UIColor().hexStringToColor(hexString: "#f17259"), for: UIControlState.normal)

代码如下:

extension UIColor {

    public func hexStringToColor(hexString: String) -> UIColor{

        var cString: String = hexString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)

        if cString.characters.count < 6 {
            return UIColor.black
        }
        if cString.hasPrefix("0X") {
            cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 2))
        }
        if cString.hasPrefix("#") {
            cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 1))
        }
        if cString.characters.count != 6 {
            return UIColor.black
        }
        
        var range: NSRange = NSMakeRange(0, 2)
        let rString = (cString as NSString).substring(with: range)
        range.location = 2
        let gString = (cString as NSString).substring(with: range)
        range.location = 4
        let bString = (cString as NSString).substring(with: range)
        
        var r: UInt32 = 0x0
        var g: UInt32 = 0x0
        var b: UInt32 = 0x0
        Scanner.init(string: rString).scanHexInt32(&r)
        Scanner.init(string: gString).scanHexInt32(&g)
        Scanner.init(string: bString).scanHexInt32(&b)
        
        return UIColor(displayP3Red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(1))

    }

你可能感兴趣的:(Swift3 写UIColor的十六进制颜色扩展—UIColor+ColorHexString)