码迷,mamicode.com
首页 > 编程语言 > 详细

swift-3.0 将HexColor转变为UIColor的方法

时间:2016-11-04 16:21:33      阅读:403      评论:0      收藏:0      [点我收藏+]

标签:rom   sed   offset   string   var   index   turn   lines   exint   

// MARK:- 把#ffffff颜色转为UIColor
extension UIColor {
    class func colorWithHexString(hex:String) ->UIColor {
        
        var cString = hex.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines).uppercased()
        
        if (cString.hasPrefix("#")) {
            let index = cString.index(cString.startIndex, offsetBy:1)
            cString = cString.substring(from: index)
        }
        
        if (cString.characters.count != 6) {
            return UIColor.red
        }
        
        let rIndex = cString.index(cString.startIndex, offsetBy: 2)
        let rString = cString.substring(to: rIndex)
        let otherString = cString.substring(from: rIndex)
        let gIndex = otherString.index(otherString.startIndex, offsetBy: 2)
        let gString = otherString.substring(to: gIndex)
        let bIndex = cString.index(cString.endIndex, offsetBy: -2)
        let bString = cString.substring(from: bIndex)
        
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        
        return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
    }
}

将以上方法直接复制粘贴至任意类中即可,调用方法如下:

 let tmpColor = UIColor.colorWithHexString(hex: "#FFFFFF") 

swift-3.0 将HexColor转变为UIColor的方法

标签:rom   sed   offset   string   var   index   turn   lines   exint   

原文地址:http://www.cnblogs.com/aProgramApe/p/6030552.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!