Hemang Hemang - 24 days ago 7
Objective-C Question

How to handle touch events and gesture events on a UIButton?

In the app, I have couple of dynamic buttons which is created and added to UITableView, each buttons having a touch event (UIControlEventTouchUpInside) and a long press gesture (UILongPressGestureRecognizer), I want to perform any one action at a time. So if when user touches only button action will be call. And if user has long pressed then long press event will be called.

Currently, it's always calling action even if I have long press on the button.

What should I do handle this events? Any good suggestions?

Answer

In order not to trigger both you should flag the button with a global variable or a tag, so in the target of UIControlEventTouchUpInside you can filter the action.

So let's assume your UILongPressGestureRecognizer calls longPress when fires, and it's initialize in your custom cell. & UIControlEventTouchUpInside calls the target btnPressed

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.button addGestureRecognizer:longPress];
[self.button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];

Selector call, inside your custom cell:

-(void)longPress:(UIButton*)btn
{
   // Flag the button,
   self.button.tag = 1;

   // Do LongPress stuff.  

}

Target of the button for UIControlEventTouchUpInside

- (void)btnPressed:(id)sender { 

    UIButton *senderButton = sender;

    if(senderButton.tag == 1) {
        // Long press has been executed, set back the flag to 0
        senderButton.tag = 0;
    } else {
        // Long press not executed 
        // Do the TouchUpInside stuff.
    }
}