Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I distinguish which part of UITableViewCell has been clicked

I have created a UITableView with a custom UITableViewCell. My cell includes one UIImageView on the left and UITextView on the right.

Inside UITableViewController, I set both image and text in tableview cellForRowAtIndexPath.

Everything shows fine but now I need to implement didSelectRowAtIndex and I need to distinguish if UIImageView or UITextView of the cell has been clicked.

Let's say, image clicking is representing delete action and the rest of the cell editing action.

like image 616
user1135839 Avatar asked Jun 17 '12 11:06

user1135839


1 Answers

Rather than adding the gesture recognisers to each individual cell, you can add one to the table view and determine which cell was selected from the point of the users touch, and then determine if the user touched the image or the cell.

First make sure your controller adopts the UIGestureRecognizerDelegate protocol.

@interface MyTableViewController() <UIGestureRecognizerDelegate>
@end

Then add the UIGestureRecognizer to the UITableView when the view loads.

    - (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    singleTap.delegate = self;
    singleTap.numberOfTapsRequired = 1;
    singleTap.numberOfTouchesRequired = 1;
    [self.tableView addGestureRecognizer:singleTap];
}

This delegate method determines if the handleTap: method should be executed. If it can find an indexPath from the users touch, then it returns YES otherwise it returns NO.

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    UITableView *tableView = (UITableView *)gestureRecognizer.view;
    CGPoint p = [gestureRecognizer locationInView:gestureRecognizer.view];
    if ([tableView indexPathForRowAtPoint:p]) {
        return YES;
    }
    return NO;
}

Once we have determined if the user has clicked in a cell, the handleTap: method is called, which then decides if the user touched the image, or any other part of the cell.

- (void)handleTap:(UITapGestureRecognizer *)tap
{
    if (UIGestureRecognizerStateEnded == tap.state) {
        UITableView *tableView = (UITableView *)tap.view;
        CGPoint p = [tap locationInView:tap.view];
        NSIndexPath* indexPath = [tableView indexPathForRowAtPoint:p];
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        CGPoint pointInCell = [tap locationInView:cell];
        if (CGRectContainsPoint(cell.imageView.frame, pointInCell)) {
            // user tapped image
        } else {
            // user tapped cell
        }
    }
}
like image 109
steharro Avatar answered Oct 11 '22 14:10

steharro