Reputation: 11320
In my gesture recognizer handler, I need to know which item on the screen the recognizer is attached to/responded to. For example, if the user taps an image, how can my handler find out which image was tapped on?
Upvotes: 0
Views: 2987
Reputation: 343
While creating a gesture recognizer, you always tie it with a view. When the gesture is detected and the selector tied with the created gesture gets called, you can use gesture.View to figure out the associated view with the gesture.
Here is the example code
UIImageView *imageView = self.someImageView;
UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageSingleTapped:)];
[imageView addGestureRecognizer:singleTapGesture];
[singleTapGesture release];
- (void) imageSingleTapped:(UIGestureRecognizer*)recognizer
{
UIView *viewTiedWithRecognizer = recognizer.view; // This is the view associated with gesture recognizer.
}
Upvotes: 9
Reputation: 42588
I had problems with that also. I don't know if I've got the right solution, but here is what I did.
CGPoint point = [gestureRecognizer locationInView:self];
CGPoint offset = self.scrollView.contentOffset;
CGPoint contentPoint = CGPointMake(point.x + offset.x, point.y + offset.y);
for (UIView *view in self.scrollView.subviews)
if (CGRectContainsPoint(view.frame, contentPoint))
return view;
return nil;
Also known as brute force.
Now that I look at it, I see a bug. It's possible that the scroll bar will be the returned view, if the user touched directly on the scroll bar. I've never had that happen (as far as I know at least), but still I should test for that and code up a solution.
Upvotes: 1