user3921894 user3921894 - 2 months ago 17
Objective-C Question

button action gets called before double tap gesture method

I've a

scrollview
on which one
button
is added, now I want to give action as well as double tap gesture to the button.

If the button is on
UIView
, both action of the button and double tap gesture methods work perfectly. But if the button is present on
UIScrollView
then action gets called followed by double tap gesture method.

Any help will be appreciated.

Answer

The scroll view needs a fair amount of touch logic to track, and that must be getting confused with the button's touch logic and your gesture recognizer.

Without investigating that further, I'd get around this by handling the button's taps via two gesture recognizers that you control, which should work no matter the parent view.

  1. Do not give the button a target/action as you normally would in IB or in code

  2. Create a single tap gesture recognizer to handle the button action.

  3. Create a double tap gr as you probably do already. Add both to the button.

    // for your current target-action behavior 
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(singleTap:)];
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(doubleTap:)];
    
    singleTap.numberOfTapsRequired = 1;
    doubleTap.numberOfTapsRequired = 2;
    [singleTap requireGestureRecognizerToFail:doubleTap];
    
    [button addGestureRecognizer:singleTap];
    [button addGestureRecognizer:doubleTap];
    

Then, instead of your IBAction method...

- (void)singleTap:(UIGestureRecognizer *)gr {
    if (gr.state == UIGestureRecognizerStateRecognized) {
        // target-action behavior here
        NSLog(@"single tapped");
    }
}

- (void)doubleTapped:(UIGestureRecognizer *)gr {
    if (gr.state == UIGestureRecognizerStateRecognized) {
        NSLog(@"double tapped");
    }
}