0

I have a UIScrollview with UIImageView's inside it.

If I add gestures to the UIImageView before they are added to the scrollview, the touch event is not fired.

I want to get the UIImageView that a tap occurs at.

I have seen some answers that touch about getting the point of the touch from the UIScrollView and then calculating the UIImageView based on the position --- but that seems really messy and overkill.

Is there a simple way to get a touch event from an object inside a UIScrollView?

Aggressor
  • 13,323
  • 24
  • 103
  • 182

2 Answers2

5

For the sake of completeness.

The UIImageView inside of UIScrollView is not programmed to receive touch events and gestures natively.

So what you may want to do is:

  1. Add UITapGestureRecognizer to the scroll view for enabling touch inside scroll view.

>

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];

singleTap.cancelsTouchesInView = NO; 

[myScrollView addGestureRecognizer:singleTap]; 
  1. Customize the UIImageView with you view inherited from UIImageView.

>

CustomImageView *imageView = [[CustomImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[imageView setUserInteractionEnabled:YES];
[scrollView addSubview:imageView];
  1. Provide touch methods in that custom subclass and add it on your UIScrollView..

>

@interface CustomImageView : UIImageView{}

@implementation CustomImageView

- (id)initWithFrame:(CGRect)frame{}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {}

@end

bllakjakk
  • 5,045
  • 1
  • 18
  • 28
2

Your UIImageViews probably have user interaction disabled (which is what they default to). Call the following line on each image view, and your taps should be recognized:

yourImageView.userInteractionEnabled = YES; 

Make sure to do this before adding the gesture recognizer.

I had this exact issue a few weeks ago and this is what fixed it for me.

Community
  • 1
  • 1
rebello95
  • 8,486
  • 5
  • 44
  • 65