在实际开发中,由UI提供的颜色值往往是十六进制字符串如“#FFFFFF”,开发者往往还需要自己去计算转换,故用Extension封装,如:
extension UIColor {
class func hexStringToColor(hex:String) ->UIColor{
var cString: String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
if(cString.hasPrefix("#")) {
cString = (cString as NSString).substring(from:1)
}
if cString.count != 6 {
return UIColor.white
}
letrString = (cString as NSString).substring(to:2)
letgString = ((cString as NSString).substring(from:2) asNSString).substring(to:2)
letbString = ((cString as NSString).substring(from:4) as NSString).substring(to:2)
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))
}
}