user4806509
user4806509

Reputation: 3011

Obtaining RGB color from UIButton (UIColor) backgroundColor in Swift

I have three UIButtons and each has a different (UIColor) backgroundColor; for example, the backgroundColor of one UIButton is blue, one is pink, the other is orange. When I click each UIButton, I want to obtain the exact RGB (Red, Green, Blue) color values directly from it's backgroundColor property. (For example, if I clicked the UIButton with the pink backgroundColor, I will get a returned RGB values- R: 255, G: 0, B: 128.) Another way to explain this is, I want to convert a UIButton's UIColor backgroundColor into UIColor RGB values.

In Swift, what is the most simple, most efficient code to extract the RGB (Red, Green, Blue) color values of a UIButton's backgroundColor and then display the result in a UILabel?

My buttons

Upvotes: 2

Views: 1010

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

Your task consists of three parts:

  • Obtaining the button that has been clicked from the click event handler
  • Given a UIButton obtain its background color, and
  • Given a UIColor obtain its RGB components

The first task is simple: add sender to the method that processes the click. The second task is also straightforward - all you need to do is accessing backgroundColor property. Finally, to get the components you need to call 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.
    } 
}

Note that it would be much simpler to do this the MVC way, i.e. by retrieving the components pre-stored in the model. Set your button tags to 0, 1, and 2, make a look-up table, and use it to perform the task:

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
}

Upvotes: 3

Related Questions