Weird behavior of UITableView method “indexPathForRowAtPoint:”

空扰寡人 提交于 2019-12-10 18:15:42

问题


As show in the following code, when the tableview is stretched (never scrolled up), the NSLog(@"tap is not on the tableview cell") will always be called (as i thought the indexPath will always be nil). But when i tap the avatar in the section header with section number greater than 2, the NSLog does not get called. It is weird, anyone know what's 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");
    }
}

回答1:


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

You could probably set the tag for the avatar view to be the section number in viewForHeaderInSection and then retrieve the section number in handleTapGesture via sender.view.tag. For example:

-(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);
}


来源:https://stackoverflow.com/questions/16946029/weird-behavior-of-uitableview-method-indexpathforrowatpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!