Tap Recognition for UIImageView in the UITableViewCell

Anatoliy Gatt picture Anatoliy Gatt · Jul 20, 2012 · Viewed 24.5k times · Source

Currently I'm facing a problem, I would like to perform action when the UIImageView on my UITableViewCell had been tapped.

Question: How could I do it? Could any one show me the code, or any tutorial?

Thanks in advance!

Answer

Mick MacCallum picture Mick MacCallum · Jul 20, 2012

This is actually easier than you would think. You just need to make sure that you enable user interaction on the imageView, and you can add a tap gesture to it. This should be done when the cell is instantiated to avoid having multiple tap gestures added to the same image view. For example:

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTapMethod:)];

        [self.imageView addGestureRecognizer:tap];
        [self.imageView setUserInteractionEnabled:YES];
    }

    return self;
}

- (void)myTapMethod:(UITapGestureRecognizer *)tapGesture
{
    UIImageView *imageView = (UIImageView *)tapGesture.view;
    NSLog(@"%@", imageView);
}