How to detect touch on UIImageView inside UIScrollview?

Ben O'Dwyer picture Ben O'Dwyer · Feb 18, 2011 · Viewed 9k times · Source

I have a UIScrollview in my app and I populate it with LOTS of UIImageViews approx 900. They are all very small and consist of only two different images over and over again.

Now I am having a lot of trouble detecting a touch on one of these UIImageViews.

I have assigned them all a unique TAG so as to be able to distinguish between them but I am really struggling to detect the touch.

The goal is just to be able to change the image of the touched UIImageView.

Due to the large amount of views involved a simple loop checking touch coordinates against each UIImageViews frame is just hanging my app.

Does anyone have any suggestions?

Thanks in Advance.

Ben

Answer

scurioni picture scurioni · Dec 20, 2011

In my case the easiest way to do it was adding a gesture recognizer:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
//Default value for cancelsTouchesInView is YES, which will prevent buttons to be clicked
singleTap.cancelsTouchesInView = NO; 
[myScrollView addGestureRecognizer:singleTap];   

Then use this method to capture the touch:

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
  { 
    CGPoint touchPoint=[gesture locationInView:myScrollView];
  }