I have this UITableView which is displaying images, downloaded rom a database, as a matrix: 4 images in each table row.
To be able to select images from the views I’m using a UITapGestureRecognizer. To make each selection unique I’ve been trying to tag each tap recognizer and each imageView. That’s where the problem is…
I’ve put a log within the for-loop that is creating and tagging the imageViews and recognizers and I can see in the output that they pass through all the values. However when I try to get the tag by later pressing an image I always get “3” (the last number in the table row). This makes me think the tags are simlpy overwriting eachother even though I’m creating a new object in each loop. Either that or I’m reading it out the wrong way.
Unrelated parts cut out.
for (NSInteger i = 0; i < 4; i++){
asyncImage = [[AsyncImageView alloc]
initWithFrame:frame];
[asyncImage loadImageFromURL:url];
asyncImage.tag = i;
NSLog(@"TAG %d", asyncImage.tag);
tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)];
tapRecognizer.view.tag = i;
NSLog(@"TapTAG %d", asyncImage.tag);
[asyncImage addGestureRecognizer:tapRecognizer];
}
And the method:
- (void)handleTap{
NSLog(@"TAP %d", self.tapRecognizer.view.tag);
}
If you think I’m doing it all totally wrong, a light push in the right direction is always welcome!
Thanks in advance, Tom
The following line has no effect until the gesture recognizer has been added to a view:
This is because
tapRecognizer‘sviewis initiallynil. Make the assignment on the last line of yourforloop to correct this problem.Also your
NSLogis always showing the tag of the last recognizer that you have addednot the one that fired the event. Change
handleTapas follows:You should also replace the
tapRecognizerinstance variable with a local variable in the method that adds the recognizer to the view, and add a colon:to your selector name: