2

I have a UIImageView which moves across the screen and I added a UITapGestureRecognizer to the image. It all works fine and dandy, however, when the image starts to move too fast across the screen, then it gets harder to tap and be recognized.

if you'll look at this image, you'll see a green square around 2 stick figures.

https://i.stack.imgur.com/3x7rT.png

Let's say, for example, you have to touch inside the green square for it to register as a "tap". Currently it's like the top image, but I would like to have some extra padding like in the bottom image. So how could I make the area of where the UITapGestureRecognizer is larger?

Xerif917
  • 132
  • 2
  • 10
  • See http://stackoverflow.com/questions/15553810/how-to-enlarge-hit-area-of-uigesturerecognizer/15554009#15554009 – rmaddy Nov 20 '13 at 04:18
  • This seemed to just change the size of my image. I want to keep the actual image size the same but have a bigger tapping radius. – Xerif917 Nov 20 '13 at 04:27
  • 1
    There is no way that code changes the size of the view. It only changes where it detects a touch event. – rmaddy Nov 20 '13 at 04:28
  • Thanks for the help guys. I figured it out though. – Xerif917 Nov 20 '13 at 19:25

1 Answers1

0

Instead of adding the tap gesture recognizer to the image view, add it to the image view's superview. Iterate over the subviews to find the view that should receive the tap gesture. For example:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView *containerView = [self view];

    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [containerView addGestureRecognizer:tapRecognizer];
}

- (void)tap:(UITapGestureRecognizer *)sender
{
    UIView *containerView = [sender view];
    CGPoint location = [sender locationInView:containerView];

    for (UIView *subview in [[containerView subviews] reverseObjectEnumerator]) {
        if (![subview isKindOfClass:[UIImageView class]]) {
            continue;
        }
        if (CGRectContainsPoint([subview frame], location)) {
            [self imageViewTapped:(UIImageView *)subview];
            return;
        }
    }
}

- (void)imageViewTapped:(UIImageView *)imageView
{
    // do something when an image view is tapped
}
Cameron Spickert
  • 5,190
  • 1
  • 27
  • 34
  • This doesn’t help unless you also expand the tappable area of the frame, perhaps using `CGRectInset(subview.frame, someNegativeFloat, someNegativeFloat)`. – Zev Eisenberg Jul 15 '14 at 21:04