How can I figure out which view was tapped on in iOS?

2 Solutions Collect From Internet About “How can I figure out which view was tapped on in iOS?”

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.

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.