Swift开发 UIColor分类Hex颜色转换

一般UI同事们给的颜色值都是16进制的,但是在iOS的UIColor中,没有直接通过Hex值进行设置颜色的接口,所以自己编写了一个接口。 

  func colorWithHexString (hex:String)-> UIColor {
        var hexString = hex
        
        if (hexString.hasPrefix("#")) {
            hexString = (hexString as NSString).substringFromIndex(1)
        }
        
        let index = hexString.startIndex.advancedBy(2)
        let index2 = hexString.startIndex.advancedBy(4)
        let range = Range(index ..< index2)
        
        let s1:String = hexString.substringToIndex(index)
        let s2:String = hexString.substringWithRange(range)
        let s3 = hexString.substringFromIndex(index2)
        
        return UIColor(red:CGFloat(hex2dec(s1))/255.0, green:CGFloat(hex2dec(s2)) / 255.0, blue:CGFloat(hex2dec(s3)) / 255.0, alpha:1)
    }
    
    func hex2dec(num:String) -> Float {
        let str = num.uppercaseString
        var sum:Float = 0
        for i in str.utf8 {
            sum = sum * 16 + Float(i) - 48 // 0-9 从48开始
            if i >= 65 {                 // A-Z 从65开始,但有初始值10,所以应该是减去55
                sum -= 7
            }
        }
        return sum
    }

Swift的Range十分的难用,不知道苹果为啥要把以前的NSRange修改到现在这么烂。。。。。。。。。


可以将上边的方法放到UIColor类扩展里:

extension UIColor {
    class func colorWithHexStringSw (hex:String)-> UIColor {
        
        func hex2dec(num:String) -> Float {
            let str = num.uppercaseString
            var sum:Float = 0
            for i in str.utf8 {
                sum = sum * 16 + Float(i) - 48 // 0-9 从48开始
                if i >= 65 {                 // A-Z 从65开始,但有初始值10,所以应该是减去55
                    sum -= 7
                }
            }
            return sum
        }
        
        var hexString = hex
        
        if (hexString.hasPrefix("#")) {
            hexString = (hexString as NSString).substringFromIndex(1)
        }
        
        let index = hexString.startIndex.advancedBy(2)
        let index2 = hexString.startIndex.advancedBy(4)
        let range = Range(index ..< index2)
        
        let s1:String = hexString.substringToIndex(index)
        let s2:String = hexString.substringWithRange(range)
        let s3 = hexString.substringFromIndex(index2)
        
        return UIColor(red:CGFloat(hex2dec(s1))/255.0, green:CGFloat(hex2dec(s2)) / 255.0, blue:CGFloat(hex2dec(s3)) / 255.0, alpha:1)
    }
}

然后就可以直接调用了:

let color = UIColor.colorWithHexStringSw("#f4f4f4")

这样就可以再整个工程里随便调用UIColor这个类型方法了~!



你可能感兴趣的:(iOS)