Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 760
CF_Maintainer Avatar asked May 03 '11 21:05

CF_Maintainer


1 Answers

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

like image 132
Jason Cragun Avatar answered Nov 16 '22 01:11

Jason Cragun