DranoMax DranoMax - 6 months ago 17
Swift Question

Listening to Swift Button Disable event

I want to set the opacity of a button to 40% when it is disabled.

Currently I'm using the following modified code I found on StackOverflow:

let disabledColor = self.backgroundColor!.colorWithAlphaComponent(0.4)
self.setBackgroundImage(self.imageForColor(disabledColor), forState: .Disabled)

private func imageForColor(color: UIColor) -> UIImage {
let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()

CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return image
}


I figured I'd be able to set the opacity on the background color I'm using and then simply create an image out of it and use it on the .Disabled state, but that doesn't do anything.

If I send something like UIColor.redColor() to imageForColor, the button changes to Red when it's disabled...however opacity appears to be ignored.

Does anyone know why this is? It'd be nice if I could just listen to the disabled event and fire my own function or if Apple would get around to letting us set Background Color for state rather than Background Image...

******EDIT******

Trying some more things, it looks like it is applying the image correctly, but it seems to be applying it over the background color and since it's the same color but with an opacity, the change is hard to notice.

I guess a solution would be to ONLY use Background Images rather than colors(?) since I can't replace the color...

Ideally, I'd like to apply opacity to the entire button on a disable event.

Answer

I think you would be best off subclassing UIButton, then overriding setEnabled so that you can manipulate the background color. See this very similar thread.

Comments