4

如以下代码所示,当 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");
    }
}
4

1 回答 1

2

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

您可以将视图设置tag为节号,然后在via中检索节号。例如:avatarviewForHeaderInSectionhandleTapGesturesender.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);
}
于 2013-06-05T17:26:20.270 回答