Andrew
Andrew

Reputation: 16051

UIScrollView with a UIButton and UITapGestureRecognizer

I've been playing around with this code, but can't get it right.

Current behaviour: I can scroll around freely on a UIScrollView, even when tapping on buttons. When i tap on something that isn't a button, it calls a method (like i want it to), as a result of a UITapGestureRecognizer. However, i have to hold down on a button for a couple of seconds then touch up for it to trigger the button's UIControlEventTouchUpInside.

What I want to happen: Exactly the same, but to be able to touch the UIButton easily, like I can if i turn off the UITapGestureRecognizer on the view it's sitting on.

Here's my code:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        //...

        [cell.xButton addTarget:self action:@selector(xButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

        self.delaysContentTouches = YES;

        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapFrom:)];
        [self addGestureRecognizer:tapGestureRecognizer];
        tapGestureRecognizer.delegate = self;
    }
}

- (void) handleTapFrom: (UITapGestureRecognizer *)recognizer
{
    [self.header removeKeyboard];
}

Upvotes: 1

Views: 1174

Answers (2)

Lorenzo B
Lorenzo B

Reputation: 33428

As stavash suggested, you could do the following:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    UIView* touchedView = [touch view];
    if([touchedView isKindOfClass:[UIButton class]]) {

       return NO;
    }

    return YES;
}

This works in most cases. In addition you may want to check whether the touched view is a descendent of a the scroll view using isDescendantOfView:.

Hope it helps.

Upvotes: 3

Stavash
Stavash

Reputation: 14304

I think your answer is UIGestureRecognizerDelegate's method:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

Check if the touch's view property is any of the UIButtons you are trying to avoid: if so return NO, otherwise return YES. Don't forget to assign the UITapGestureRecognizer's delegate so it works. Hope this helps.

Upvotes: 2

Related Questions