Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
}

One way you could do it is by creating a UIImageView from your image and add a gesture recognizer to it. See the example below

//Create ImageView
UIImageView *theImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"emptystar1.png"]];
theImageView.userInteractionEnabled = YES;

//Add Gesture Recognizer
UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageSelectedInTable)];
tapped.numberOfTapsRequired = 1;
[theImageView addGestureRecognizer:tapped];
[cell addSubview:theImageView];

//Memory Cleanup
[tapped release];
[theImageView release];

-(void)imageSelectedInTable
{
    NSLog(@"Selected an Image");
}

However, you'll now have to layout your cells more since you can't simply use the UIImageView property of the UITableViewCell since it's readonly.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!