joey
joey

Reputation: 33

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

In my tableView cell i have:

cell.imageView.image = image;

How can I detect the user click directly on that image, and not the cell.textLabel?

Upvotes: 3

Views: 2071

Answers (2)

Matthias Bauch
Matthias Bauch

Reputation: 90117

Add a UITapGestureRecognizer 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);
}

Upvotes: 5

csano
csano

Reputation: 13686

As some of the comments have pointed out, you should use an UIButton instead. A UIImageView is not designed to handle user interaction out of the box and it's much simpler to just create a button, add a target, and add it as a subview of the cell.

Upvotes: 1

Related Questions