Search code examples
iosswiftuibuttonuilabeluicolor

fading the UIColor with a buttonPress


I am making an interactive app which is supposed to display a UILabel of a blue color which must fade when a certain button is pressed. As we keep pressing the button, the color should of the label should fade. I tried creating a custom UIColor and changing it's brightness but it's not really effective. It fades for a few button presses after which the color does not change at all.

What is the best way to achieve my goal? Any help would be appreciated. It's a simple task but becoming annoying for no reason.

here is the code for what i am doing. "tube" is the UILabel whose background color is supposed to fade as the int "count" keeps increasing.

var intensity : CGFloat = 0.3         
@IBAction func fa(sender: AnyObject) {

    let five = UIColor(hue: 0.61, saturation: 0.31, brightness: 0.76, alpha: intensity)
    let four = UIColor(hue: 0.61, saturation: 0.31, brightness: 0.65, alpha: intensity)
    let three = UIColor(hue: 0.61, saturation: 0.31, brightness: 0.59, alpha: intensity)
    let two = UIColor(hue: 0.61, saturation: 0.31, brightness: 0.53, alpha: intensity)
    let one = UIColor(hue: 0.61, saturation: 0.31, brightness: 0.37, alpha: intensity)



    count += 1

    if (count == 0){
        tube.backgroundColor = UIColor(red: 109, green: 132, blue: 180, alpha: 0.2)
    }
    else if (count == 1){
        tube.backgroundColor = one
        print("one")
    }

    else if (count == 2 ){
        tube.backgroundColor = two
        print("two")
    }

    else if (count == 3){
        tube.backgroundColor = three
        print("three")
    }

    else if (count == 4){
        tube.backgroundColor = four
    }

    else if (count == 5){
        tube.backgroundColor = five
    }
    else {
        tube.backgroundColor = UIColor(red: 109, green: 132, blue: 180, alpha: 0.2)
    }

Solution

  • Assuming that the ViewController background is white, you can fade the background color by actually fading either the button itself or the alpha value of the color.

    To change the opacity of the button, use the following code:

    if tube.layer.opacity > 0 {
        tube.layer.opacity -= 0.1
    }
    

    If you want to fade the color instead, you have to extract RGB values (see this answer) from the previous color and change its alphaValue while recreating it.