swift - Swift 中从 UIButton (UIColor) backgroundColor 获取 RGB 颜色

标签 swift optimization uibutton background-color

我有三个 UIButton,每个都有不同的 (UIColor) backgroundColor;例如,一个UIButtonbackgroundColor是蓝色,一个是粉色,另一个是橙色。当我单击每个 UIButton 时,我想直接从其 backgroundColor 属性获取准确的 RGB(红、绿、蓝)颜色值。 (例如,如果我单击带有粉红色 backgroundColorUIButton,我将获得返回的 RGB 值 - R:255、G:0、B:128。)解释一下,我想将 UIButton 的 UIColor backgroundColor 转换为 UIColor RGB 值。

在 Swift 中,提取 UIButtonbackgroundColor 的 RGB(红、绿、蓝)颜色值的最简单、最有效的代码是什么在 UILabel 中显示结果?

My buttons

最佳答案

您的任务由三个部分组成:

  • 从点击事件处理程序中获取已被点击的按钮
  • 给定一个 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/

相关文章:

ios - 无法将 UIButton 添加到 UIScrollView

iphone - iPhone-在UILabel中设置图标和文本

ios - 如何搜索经过身份验证的用户 Firebase iOS Swift

ios - 当应用程序被终止(非事件)时,点击 Firebase 通知不起作用

ios - 如何成功传递字符串数组作为参数 alamofire

mysql - 使用单个查询选择和删除

ios - 设备人脸识别 - Swift

python-iptables如何优化代码

python - 如何正确设置带有约束和多个最优值的 scipy.optimize 最小化?

swift - 单击 uicollection 单元格中的按钮进行继续