Strange behavior of the UITableView method "indexPathForRowAtPoint:"

As the following code shows, when a tableview is stretched (never scrolls), NSLog(@"tap is not on the tableview cell") will always be called ( because I thought indexPath would always be nil ). But when I click the avatar in the section header with a section number greater than 2, NSLog not called. Strange, does anyone know what is going on here?

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { ... UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]; tapGesture.numberOfTapsRequired = 1; [avatar addGestureRecognizer:tapGesture]; //avatar is UIImageView and the user interaction is enabled. [headerView addSubview: aMessageAvatar]; return headerView; ... } -(void)handleTapGesture:(UITapGestureRecognizer *)sender { CGPoint point = [sender locationInView:self.tableView]; NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:point]; if (!indexPath) { NSLog(@"tap is not on the tableview cell"); } } 
+4
source share
1 answer

Your tap position is the location in the header, not the cell, so it will never match the indexPath cell.

Perhaps you could set the tag to represent avatar as the section number in viewForHeaderInSection , and then get the section number in handleTapGesture via sender.view.tag . For instance:

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { ... UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]; tapGesture.numberOfTapsRequired = 1; avatar.tag = section; // save the section number in the tag avatar.userInteractionEnabled = YES; // and make sure to enable touches [avatar addGestureRecognizer:tapGesture]; //avatar is UIImageView and the user interaction is enabled. [headerView addSubview: aMessageAvatar]; return headerView; ... } -(void)handleTapGesture:(UITapGestureRecognizer *)sender { NSInteger section = sender.view.tag; NSLog(@"In section %d", section); } 
+2
source

Source: https://habr.com/ru/post/1484690/


All Articles