2

I have a UITextView subclass that has an NSIndexPath property that is inside a UITableViewCell. When you tap on it, I'd like to be able to call didSelectRowAtIndexPath.

Here's what I have:

UITapGestureRecognizer *singleFingerTap = 
[[UITapGestureRecognizer alloc] initWithTarget:self action:nil];
[theTextView addGestureRecognizer:singleFingerTap];
singleFingerTap.delegate = self;

....

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    CustomTextView *theTextView = (CustomTextView *)touch.view;

    NSLog(@"%@", theTextView.indexPath);


    return YES;

}

I see from this question, I may even have to break up my didSelectRowAtIndexPath logic, which is fine. And I already know the index path of the view that was tapped.

What is the proper way to call this tableView method (or what didSelectRowAtIndexPath would do) from within the gesture recognizer method?

Community
  • 1
  • 1
barfoon
  • 27,481
  • 26
  • 92
  • 138

2 Answers2

2

I answered a similar question here. Basically when you call:

[tableView selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionNone];

the tableview doesn't fire the tableView:didSelectRowAtIndexPath: on the tableview's delegate, so in addition you are forced to directly call (And since you wrote the code in the delegate method there's no problem):

[tableView.delegate tableView:tableView didSelectRowAtIndexPath:path];

Also your passing nil for the action is really not how gesture-recognizers where mean to work:

[[UITapGestureRecognizer alloc] initWithTarget:self action:nil];

Generally you would do something like this:

[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)];

That basically tells the gesture recognizer to call the tapRecognized: method when it receives a tap. So basically to wrap it all up (I'm assuming this is in a UITableViewController or an object with a property named tableView as UITableViewControllers have by default).

-(void)tapRecognized:(UITapGestureRecognizer *)tapGR{
    // there was a tap
    CustomTextView *theTextView = (CustomTextView *)tapGR.view;
    NSIndexPath *path = theTextView.indexPath;
    [self.tableView selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionNone];
    [self.tableView.delegate tableView:self.tableView didSelectRowAtIndexPath:path];
}
Community
  • 1
  • 1
NJones
  • 27,139
  • 8
  • 70
  • 88
1

If you need to do X both in response to a gesture and to a tap on a table view row, simply create a method X and call that from your gesture recognizer method as well as from your didSelectRowAtIndexPath table view delegate method.

Of course, theoretically,

[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];

would work, but I think calling the delegate method yourself is bad style to say the least.

Mundi
  • 79,884
  • 17
  • 117
  • 140