swift中变量中的UIColor代码 [英] UIColor code in a variable in swift

查看:27
本文介绍了swift中变量中的UIColor代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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) 

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

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

推荐答案

如果 hex 是 Int 而不是 String 你可以使用这个扩展:

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

像这样使用:

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

这篇关于swift中变量中的UIColor代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆