通過給UIColor或者String添加extension都可以實現,以下列出兩種方法:
給String添加extension
extension String{
/// 將十六進制顏色轉偉UIColor
/// - Returns: UIColor
public func toUIColor() -> UIColor {
//處理數值
var cString = self.uppercased().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let length = (cString as NSString).length
//錯誤處理
if (length < 6 || length > 7 || (!cString.hasPrefix("#") && length == 7)){
return UIColor.white
}
if cString.hasPrefix("#"){
cString = (cString as NSString).substring(from: 1)
}
//字符chuan截取
var range = NSRange()
range.location = 0
range.length = 2
let rString = (cString as NSString).substring(with: range)
range.location = 2
let gString = (cString as NSString).substring(with: range)
range.location = 4
let bString = (cString as NSString).substring(with: range)
//存儲轉換后的數值
var r:UInt32 = 0,g:UInt32 = 0,b:UInt32 = 0
//進行轉換
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
//根據顏色值創(chuàng)建UIColor
return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
}
}
給UIColor添加extension
extension UIColor{
convenience init(hexString:String){
//處理數值
var cString = hexString.uppercased().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let length = (cString as NSString).length
//錯誤處理
if (length < 6 || length > 7 || (!cString.hasPrefix("#") && length == 7)){
//返回whiteColor
self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
return
}
if cString.hasPrefix("#"){
cString = (cString as NSString).substring(from: 1)
}
//字符chuan截取
var range = NSRange()
range.location = 0
range.length = 2
let rString = (cString as NSString).substring(with: range)
range.location = 2
let gString = (cString as NSString).substring(with: range)
range.location = 4
let bString = (cString as NSString).substring(with: range)
//存儲轉換后的數值
var r:UInt32 = 0,g:UInt32 = 0,b:UInt32 = 0
//進行轉換
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
//根據顏色值創(chuàng)建UIColor
self.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
}
}