سؤال

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");
    }
}
هل كانت مفيدة؟

المحلول

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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top