UITableView方法“indexPathForRowAtPoint:”的奇怪行为

时间:2013-06-05 17:15:20

标签: ios uitableview nsindexpath

如下面的代码所示,当tableview被拉伸(从不向上滚动)时,将始终调用NSLog(@"tap is not on the tableview cell")因为我认为indexPath将始终为nil )。但是当我点击截面编号大于2的节标题中的头像时,NSLog不会被调用。这很奇怪,有谁知道这里发生了什么?

-(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 个答案:

答案 0 :(得分:2)

您的点击位置是标题中的位置,而不是单元格,因此它永远不会与单元格indexPath匹配。

您可以将tag视图的avatar设置为viewForHeaderInSection中的部分编号,然后通过handleTapGesture检索sender.view.tag中的部分编号。例如:

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