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

Posted 思微随想

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将十六进制的颜色字符串转为UIColor相关的知识,希望对你有一定的参考价值。

扩展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的主要内容,如果未能解决你的问题,请参考以下文章

iOS工具种之16进制颜色转为UIColor

ios 怎么把颜色转为16进制

如何在 Swift 中创建十六进制颜色字符串 UIColor 初始化程序? [复制]

UIColor与十六进制字符串互转

UIColor支持16进制颜色设置

UIColor使用16进制颜色