Search code examples
iphoneuiscrollviewuiimageviewuitouch

unable to get touch event delegate method on touch of uiimageview


I have added some uiimageview in a scrolview and now want to perform some action on touch on it uiimageview. But my touch delegates methods are not being called up. Following is my code:

int x = 0;
for (int i = 0; i < [arr count]; i++){
    UIImageView *myImageview = [[UIImageView alloc] initWithFrame:CGRectMake(x, 0, 320, self.view.frame.size.height-45)];
    myImageview.userInteractionEnabled = TRUE;
    myImageview.opaque = YES;
    //[myImageview setImage:[arr objectAtIndex:i]];
    myImageview.tag = 100+i;
    [scrollvw addSubview:myImageview];
    [myImageview setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[(NSDictionary*)[arr objectAtIndex:i] objectForKey:@"image"]]] placeholderImage:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
        //reload data here
        myImageview.image = image;


    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
        //handle errors here
    }];

    x += myImageview.frame.size.width;

}

[scrollvw setContentSize:CGSizeMake(x, self.view.frame.size.height-45)];

I have added following method but it does not work:

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

UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];

if (touch.view.tag > 0) {
    touch.view.center = location;
}

NSLog(@"tag=%@", [NSString stringWithFormat:@"%i", touch.view.tag]);

}

Can some one please help me in getting the touch delegate method called.

Regards
Pankaj


Solution

  • Why not just add a UITapGestureRecognizer onto your image like this:

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(testMethod:)];
    
    [myImageview addGestureRecognizer:tap];
    
    - (void)testMethod:(id)sender {
        UIImageView *sent = (UIImageView *)sender;
    
        NSLog(@"Image Tag: %d", sent.tag);
    }