Change color of the view using RGB value or hex value of color in swift

2.9k Views Asked by At

I got the following code on internet and I used this piece of code in my project to change the color of the background.

// 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))
}

When I called the above function as follows to change the color of background:

lbl91.backgroundColor = colorWithHexString(hex: 0x209624);

it gives me following error:

cannot convert the expression's type '()' to type integerliteralconvertible
1

There are 1 best solutions below

0
On BEST ANSWER

The function expects its parameter like this:

colorWithHexString("#ff00dd")

or without the hashtag

colorWithHexString("ff00dd")