使用 swift 中颜色的 RGB 值或十六进制值更改视图颜色
Change color of the view using RGB value or hex value of color in swift
我在网上得到了下面的代码,我在我的项目中使用了这段代码来改变背景的颜色。
// Creates a UIColor from a Hex string.
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (countElements(cString) != 6) {
return UIColor.grayColor()
}
var rString = (cString as NSString).substringToIndex(2)
var gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
var 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))
}
当我调用上面的函数改变背景颜色时:
lbl91.backgroundColor = colorWithHexString(hex: 0x209624);
它给我以下错误:
cannot convert the expression's type '()' to type integerliteralconvertible
该函数需要这样的参数:
colorWithHexString("#ff00dd")
或没有主题标签
colorWithHexString("ff00dd")
我在网上得到了下面的代码,我在我的项目中使用了这段代码来改变背景的颜色。
// Creates a UIColor from a Hex string.
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (countElements(cString) != 6) {
return UIColor.grayColor()
}
var rString = (cString as NSString).substringToIndex(2)
var gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
var 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))
}
当我调用上面的函数改变背景颜色时:
lbl91.backgroundColor = colorWithHexString(hex: 0x209624);
它给我以下错误:
cannot convert the expression's type '()' to type integerliteralconvertible
该函数需要这样的参数:
colorWithHexString("#ff00dd")
或没有主题标签
colorWithHexString("ff00dd")