Detect single tap on UIScrollView containing 'n' UIImageViews

I am simply trying to get hold of the UIImageView that was tapped on, from the UIScrollView.

I have found 2 ways of achieving the above on the Web.

1st method : create a tap gesture on the uiimageview before adding it to scrollviewer.

This method has not worked for me. the handleSingleTap method never gets called.

I am out of ideas on what I am doing wrong/why this is not working.

    UITapGestureRecognizer *singleTap = 
    [[UITapGestureRecognizer alloc] initWithTarget:self 
    action:@selector(handleSingleTap:)];
        singleTap.numberOfTapsRequired = 1;
        [imageView addGestureRecognizer:singleTap];
        [singleTap release];

        [framesSourceScrollview addSubview:imageView];
        [imageView release];

            - (void)handleSingleTap:(UIGestureRecognizer *)sender
            {   
                NSLog(@"image tapped!!!");
            }

2nd Method : subclass UIScrollView

@interface SingleTapScrollViewer : UIScrollView {
}
@end

@implementation SingleTapScrollViewer

- (id)initWithFrame:(CGRect)frame 
{
    return [super initWithFrame:frame];
}

- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event 
{   
    // If not dragging, send event to next responder
    if (!self.dragging) 
        [self.nextResponder touchesEnded: touches withEvent:event]; 
    else
        [super touchesEnded: touches withEvent: event];
}
@end

In the ViewController

- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event 
{
    // Process the single tap here
    NSLog(@"Scroll view single tapped. touches count : %d", touches.count);
UITouch *touch = [touches anyObject]; 
    UIImageView *imgView = (UIImageView*)touch.view;
    NSLog(@"tag is %@", imgView.tag);
}

Using this method, the touchesDown responder does get called but the '[touches anyobject]' isn't the UIImageView which was tapped on.

I tried setting the 'tag' on every UIImageView I am adding to the scrollview with an increasing counter but I get back 0 no matter which imageview i tap on.

I am new to cocoa in general and I am not sure how to leverage this responder in any other fashion.

Any suggestions/hints would be great.

thanks in advance.

Answers


did you set the userInteractionEnabled=YES on the UIImageView. Its turned off by default.


Need Your Help

Copy and paste from one workbook to another

excel vba excel-vba

I have code in one workbook, this should open another workbook, copy and paste into the workbook with the code. I can select the data but can't paste it.

Algorithm to find two repeated numbers in an array, without sorting

algorithm search

There is an array of size n (numbers are between 0 and n - 3) and only 2 numbers are repeated. Elements are placed randomly in the array.