How to detect if the user clicks directly on cell.imageView and not on the shortcut in the tableview cell?

In my tableView cell, I have:

cell.imageView.image = image;

How can I determine how the user clicks directly on this image, and not on cell.textLabel?

+3
source share
2 answers

Add the UITapGestureRecognizer identifier to the imageView.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    /* ... */
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.imageView.image = /*...*/

        UITapGestureRecognizer *tapGesture = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)] autorelease];
        [cell.imageView addGestureRecognizer:tapGesture];
        cell.imageView.userInteractionEnabled = YES;
    }
    /* ... */
}

- (void)imageTapped:(UITapGestureRecognizer *)gesture {
    UITableViewCell *cell = [[[gesture view] superview] superview];
    NSIndexPath *tappedIndexPath = [self.tableView indexPathForCell:cell];
    NSLog(@"Image Tap %@", tappedIndexPath);
}
+5
source

As noted in some comments, it should be used instead UIButton. A is UIImageViewnot designed to handle user interaction out of the box, and it’s much easier to just create a button, add a target and add it as a cell spy.

+1
source

All Articles