Andrew Lauer Barinov
Andrew Lauer Barinov

Reputation: 5754

Multiple Gesture Responders for a Single View

I have an image that I would like to set up to respond to several different gesture responders. So for example, if one part of the picture is touched I would like one selector to be called, and another selector for a different part of the picture.

I looked at the UIGestureRecognizer and UITapGestureRecognizer classes, but I couldn't find a way to specify the image zones to be associated with them. Is this at all possible in iOS? And if so what classes should I look into using?

Upvotes: 0

Views: 1903

Answers (2)

Mark Adams
Mark Adams

Reputation: 30846

Use the locationInView: property to determine where your tap occurred and then conditionally invoke a method. You can do this by setting up some CGRects that correspond to your hit areas. Then use the CGRectContainsPoint() function to determine if the tap landed in one of the hit areas.

Your tap gesture recognizer action may look something like this:

- (void)tapGestureRecognized:(UIGestureRecognizer *)recognizer
{
    // Specify some CGRects that will be hit areas
    CGRect firstHitArea = CGRectMake(10.0f, 10.0f, 44.0f, 44.0f);
    CGRect secondHitArea = CGRectMake(64.0f, 10.0f, 44.0f, 44.0f)

    // Get the location of the touch in the view's coordinate space
    CGPoint touchLocation = [recognizer locationInView:recognizer.view];

    if (CGRectContainsPoint(firstHitArea, touchLocation))
    {
        [self firstMethod];
    }
    else if (CGRectContainsPoint(secondHitArea, touchLocation))
    {
        [self secondMethod];
    }
}

Upvotes: 2

matt
matt

Reputation: 534885

The easiest solution is to lay invisible views over the image and put the gesture recognizers on them.

If that's not feasible you'll have to look at the locationInView in the gesture recognizer's tap handler and figure out what you want to do based on where the user tapped.

Upvotes: 3

Related Questions