How to detect touches on UIImageView of UITableViewCell object in the UITableViewCellStyleSubtitle style
In your cellForRowAtIndexPath
method add this code
cell.imageView.userInteractionEnabled = YES;
cell.imageView.tag = indexPath.row;
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myFunction:)];
tapped.numberOfTapsRequired = 1;
[cell.imageView addGestureRecognizer:tapped];
[tapped release];
And then to check which imageView
was clicked, check the flag in selector
method
-(void)myFunction :(id) sender
{
UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;
NSLog(@"Tag = %d", gesture.view.tag);
}
The accepted solution is currently broken in iOS 5.0. The bug causes the image view's gesture recognizer to never be triggered. Through research on the official developer forums I found that this is a known bug in iOS 5.0. It is caused by an internal implementation that causes -gestureRecognizerShouldBegin:
to return NO. The bug appears when you are setting the gesture recognizer's delegate to the custom UITableViewCell
subclass itself.
The fix is to override -gestureRecognizerShouldBegin:
in the gesture recognizer's delegate and return YES. This bug should be fixed in a future version of iOS 5.x. This is only safe as long as you are not using the new UITableViewCell copy/paste API's.
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
return YES;
}
For Swift, in your cellForRowAtIndexPath method add this code
cell.imageView?.userInteractionEnabled = true
cell.imageView?.tag = indexPath.row
var tapped:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "TappedOnImage:")
tapped.numberOfTapsRequired = 1
cell.imageView?.addGestureRecognizer(tapped)
And then to check which imageView was clicked, check the flag in selector method
func TappedOnImage(sender:UITapGestureRecognizer){
println(sender.view?.tag)
}