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

时间:2024-04-19 20:35:50

扩展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")