我有三个 UIButton
,每个都有不同的 (UIColor) backgroundColor
;例如,一个UIButton
的backgroundColor
是蓝色,一个是粉色,另一个是橙色。当我单击每个 UIButton
时,我想直接从其 backgroundColor
属性获取准确的 RGB(红、绿、蓝)颜色值。 (例如,如果我单击带有粉红色 backgroundColor
的 UIButton
,我将获得返回的 RGB 值 - R:255、G:0、B:128。)解释一下,我想将 UIButton
的 UIColor backgroundColor
转换为 UIColor RGB 值。
在 Swift 中,提取 UIButton
的 backgroundColor
的 RGB(红、绿、蓝)颜色值的最简单、最有效的代码是什么在 UILabel
中显示结果?
最佳答案
您的任务由三个部分组成:
- 从点击事件处理程序中获取已被点击的按钮
- 给定一个
UIButton
获取其背景颜色,并且 - 给定一个
UIColor
获取其 RGB 分量
第一个任务很简单:将 sender
添加到处理点击的方法中。第二个任务也很简单 - 您所需要做的就是访问 backgroundColor
属性。最后,要获取需要调用 getRGB
的组件。
@IBAction func mainButton(button: UIButton) {
let bgColor:UIColor = button.backgroundColor!
var r : CGFloat = 0
var g : CGFloat = 0
var b : CGFloat = 0
var a: CGFloat = 0
if bgColor.getRed(&r, green: &g, blue: &b, alpha: &a) {
... r, g, b, and a represent the component values.
}
}
请注意,使用 MVC 方式执行此操作会简单得多,即通过检索模型中预存储的组件。将按钮标签设置为 0、1 和 2,创建一个查找表,然后使用它来执行任务:
let componentForTag: Int[][] = [[255, 0, 128], [128, 0, 0],[128, 128, 0]]
...
@IBAction func mainButton(button: UIButton) {
let components = componentForTag[button.tag]
// That's it! components array has the three components
}
关于swift - Swift 中从 UIButton (UIColor) backgroundColor 获取 RGB 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709299/