Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exclude subview from UITapGestureRecognizer

I have a subview and a superview. The superview has an UITapGestureRecognizer attached to it.

UIView *superview = [[UIView alloc] initWithFrame:CGRectMake:(0, 0, 320, 480);
UIView *subview = [[UIView alloc] initWithFrame:CGRectMake:(100, 100, 100, 100);
UIPanGestureRecognizer *recognizer = [[UIPanGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap);
superview.userInteractionEnabled = YES;
subview.userInteractionEnabled = NO;
[superview addGestureRecognizer:recognizer];
[self addSubview:superview];
[superview addSubview:subview];

The recognizer is fired inside the subview as well, is there a way to exclude the recognizer from the subview?



I know this question has been asked before but I didn't find a good answer to it.

like image 433
Wilhelm Michaelsen Avatar asked Jul 05 '13 13:07

Wilhelm Michaelsen


2 Answers

You can use gesture recognizer delegate to limit area where it can recognise touches similar to this example:

recognizer.delegate = self;
...

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    CGPoint touchPoint = [touch locationInView:superview];
    return !CGRectContainsPoint(subview.frame, touchPoint);
}

Note that you need to keep reference to your parent and child view (make them instance variables?) to be able to use them in delegate method

like image 77
Vladimir Avatar answered Oct 21 '22 01:10

Vladimir


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if(touch.view == yourSubview)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

Thanks : https://stackoverflow.com/a/19603248/552488

like image 3
Jonathan Avatar answered Oct 21 '22 01:10

Jonathan