Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a UIButton 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 UITapGestureRecognizer to the UIButton but it doesn't respond when the button is in a disabled state.

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

like image 994
devios1 Avatar asked Sep 09 '14 22:09

devios1


1 Answers

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.

like image 94
rob mayoff Avatar answered Sep 17 '22 23:09

rob mayoff