Quirk of the day - UIButton states and Images

UIButtons and I don't seem to get on. Embarrassing but true. Controls don't come much simpler than a button, but I still have spent an inordinate amount of time wrestling with them.

My latest episode of button distraction was trying to get a button to show different images in two states. Simple, right? Done it many times before. You just set different images for different states and toggle the states. I traditionally use the selected state for this.

First attempt

That works fine ... until I disabled the button while selected. At that point the button showed a greyed-out version of the unselected image. When enabled again the selected image came back.

So I spent some time making sure that I wasn't toggling the selected state myself as part of the disable/enable logic. No that wasn't the problem.

Time for something new and radical - I reread the documentation and thought about was what was going on.

As often happens the reason for the behaviour is simple and obvious ... disabled is just another state and it gets added (or'ed actually) into the button's state. Disabled | selected is not the same as selected so my explicit selected image was not used.

The obvious solution was to set the same image for selected | disabled as well. As with many obvious solutions, it was wrong.

Second attempt

Now when I disabled the button I got the right image, but it wasn't greyed out in the normal manner for disabled buttons! Apparently greying-out the image is only the behaviour when an image is not specified for the disabled state and the normal state image is being used.

Of course this makes sense. In most cases when you explicitly specify a disabled image you want to use that image as is, not have a greyed-out version forced upon you.

I could see two alternatives - (1) create a greyed-out version of my selected icon for use when disabled, or (2) abandon using the selected state mechanism completely and set the image for the normal state as required and let the default disable behaviour grey them out.

Unsatisfactory result

Fiddling around with another icon image and getting it to match the system generated greyed-out icons seemed like a lot of work and destined to not look quite right, so I went with option 2.

Not a particularly satisfying resolution as instinctively it feels a bit clunky, but it works and I now know a little more about button behaviour than I did.