devios devios -5 years ago 137
iOS Question

What's the simplest way to receive tap events on a disabled UIButton?

I have a

on a form, and want to put it in a disabled state when the form is incomplete. However, I still want to be able to detect if a user attempts to press the button even in its disabled state so that the interface can let the user know that certain required fields on the form are not filled-in yet (and perhaps scroll to that field and point it out, etc.).

There doesn't seem to be any straightforward way to do this. I tried simply attaching a
to the
but it doesn't respond when the button is in a disabled state.

I'd like to avoid subclassing
if possible, unless it's the only way.

Answer Source

Create a fallback button. Put it behind the main button. Set its background and text colors to [UIColor clearColor] to ensure it won't show up. (You can't just set its alpha to 0 because that makes it ignore touches.) In Interface Builder, the fallback button should be above the main button in the list of subviews, like this:

buttons in subview list

Give it the same frame as the main button. If you're using autolayout, select both the main and fallback buttons and create constraints to keep all four edges equal.

When the main button is disabled, touches will pass through to the fallback button. When the main button is enabled, it will catch all the touches and the fallback button won't receive any.

Connect the fallback button to an action so you can detect when it's tapped.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download