恩格贝
2015-03-11 17:33
请问老师在swift 语言中怎样直接使用16进制的色值
func UIColorFromRGB (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
let rString = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(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: CGFloat(1))
}
eg:
self.setTitleColor(UIColorFromRGB("0xec8c00"), forState: .Selected)
已用粗体标出。
func UIColorFromRGB (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substring(from: 1)
}
let rString = (cString as NSString).substring(to: 2)
let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
let bString = ((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))
}
这些需要改动的。
亲测,可以使用谢谢!不过swift3的语法略微有些变化,需要稍微修改下。
这个还需要转换成UIColor里面三色才能使用
玩儿转Swift
57181 学习 · 511 问题
相似问题