码迷,mamicode.com
首页 > 其他好文 > 详细

将十六进制的颜色字符串转为UIColor

时间:2016-06-22 23:22:39      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

扩展UIColor,将十六进制的颜色字符串转成UIColor对象。

extension UIColor {
    
    static func colorWithHexString(hex:String) -> UIColor {
        var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
        
        if cString.hasPrefix("#") {
            let index:String.CharacterView.Index = cString.startIndex.advancedBy(1)
             cString = cString.substringFromIndex(index)
        }
        
        if cString.characters.count != 6 {
            return UIColor.grayColor()
        }
        
        //按两位分割字符内容
        let rString = cString.substringToIndex(cString.startIndex.advancedBy(2))
        let gString = cString.substringFromIndex(cString.startIndex.advancedBy(2)).substringToIndex(cString.startIndex.advancedBy(2))
        let bString = cString.substringFromIndex(cString.startIndex.advancedBy(4)).substringToIndex(cString.startIndex.advancedBy(2))
        
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0
        NSScanner(string: rString).scanHexInt(&r)
        NSScanner(string: gString).scanHexInt(&g)
        NSScanner(string: bString).scanHexInt(&b)
        
        return UIColor(red: CGFloat(r) / 255.0 , green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1)
    }
}

 现在就可以调用了,

self.view.backgroundColor = UIColor.colorWithHexString("#ffff00")

 

将十六进制的颜色字符串转为UIColor

标签:

原文地址:http://www.cnblogs.com/foxting/p/5608737.html

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