Swift中变量的UIColor代码

时间:2015-07-04 06:41:11

标签: swift uicolor

我想通过参数设置视图的背景颜色,这样当1想要更改它时我可以更改它。参数的值来自数据库。我目前的代码如下:

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

我想更改上面的代码如下:

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

                                 or

loadingView.backgroundColor = UIColor(hex) 

其中a,b,c,d和hex是变量,所有这些都有一个值。

2 个答案:

答案 0 :(得分:3)

如果hex是Int而不是String,您可以使用此扩展名:

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

像这样使用:

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

答案 1 :(得分:2)

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

测试

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)