Amit Raj
Amit Raj

Reputation: 1378

UIColor code in a variable in swift

I want to set the background color of view through a parameter so that when 1 want to change it I can change it. The value of the parameter is coming from database. My current code is like follows:

loadingView.backgroundColor = UIColor(red:0.99, green:0.75, blue:0.14, alpha:1.0) 

I want to change the above code as follows:

loadingView.backgroundColor = UIColor(red:a, green:b, blue:c, alpha:d)

                                 or

loadingView.backgroundColor = UIColor(hex) 

Where a, b, c, d and hex are variables and all of these have a value.

Upvotes: 3

Views: 3743

Answers (2)

Arbitur
Arbitur

Reputation: 39081

If hex is an Int and not a String you can use this extension:

extension UIColor {
    convenience init(hex: Int, alpha: CGFloat) {
        let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
        let green = CGFloat((hex & 0xFF00) >> 8) / 255.0
        let blue = CGFloat((hex & 0xFF)) / 255.0
        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }
}

Used like this:

UIColor(0x00ff00, alpha: 1.0)
UIColor(hex, alpha: 1.0)

Upvotes: 3

Leo Dabus
Leo Dabus

Reputation: 236350

extension String {
    subscript(range: Range<Int>) -> String {
        return substringWithRange(advance(startIndex,range.startIndex)..<advance(startIndex,range.endIndex))
    }
}
extension UIColor {
    convenience init(htmlColor:String, alpha: Double) {
        self.init(red: CGFloat( strtoul(htmlColor[0...1], nil, 16) )/255.0,
                green: CGFloat( strtoul(htmlColor[2...3], nil, 16) )/255.0,
                 blue: CGFloat( strtoul(htmlColor[4...5], nil, 16) )/255.0,
                alpha: CGFloat( alpha )
        )
    }
}

Testing

let greenColorHEX = "00ff00"
let greenColor = UIColor(htmlColor: greenColorHEX, alpha: 1)

let a:CGFloat = 1
let b:CGFloat = 1
let c:CGFloat = 0
let d:CGFloat = 1

let yellowColor = UIColor(red: a, green: b, blue: c, alpha: d)

Upvotes: 2

Related Questions