How to prevent double tap on UIButton

If you Google this question you will get a lot of wrong answers, which may be marked as right answers on Stackoverflow. The simplest “solution” is to disable the button temporarily inside its action method.

For instance:

-(IBAction) buttonTapped: (UIButton *) sender{

   sender.enabled = NO;

   //or

   sender.userInteractionEnabled=YES;

   //do something here

}

But from my experience this approach doesn’t work. The reason is that UIKit framework doesn’t perform your commands immediately: it decides on its own when the right time to do what you ask it to do is. I read about it somewhere a long time ago and I don’t have any links now, so feel free to correct me if I’m wrong. But that’s what I have encountered many times in my work. And it’s strange that nobody on the internet is talking about it. That’s why I wonder if I overlooked something, but anyway…

Here is the solution that I use. I create a BOOL variable or a property on my view controller. Then I just use this flag instead of enabled property of UIButton.

@interface MyViewController (){

BOOL disableButton;

}

@end

@implementation MyViewController

-(IBAction) buttonPressed: (UIButton *) sender{

   if(disableButton)return;

   disableButton = YES;

   //do something here

}

@end

Of course, you must enable the button later by setting the BOOL variable to NO.

Leave a Reply

Your email address will not be published. Required fields are marked *