Ios – Add a gesture recognizer to tableView header doesn’t work

iosios5uigesturerecognizer

I know that a "table view header"(the most top-part of a table view) is a View
So I try to add a UITapGestureRecognizer to it ,but it doesn't work…

code is simple :

- (void)tap:(UITapGestureRecognizer *)recognizer
{
    // do something
}

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]    initWithTarget:self action:@selector(tap:)];
[self.tableView.tableHeaderView addGestureRecognizer:recognizer];

Any tips here to care ? thanks a lot

Best Answer

Here's the thing that works for me: Instead adding this:

self.tableView.tableHeaderView

I add gesture recognizer on every UILabel on tableview.

    -(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UILabel *headerLabel = [[UILabel alloc]init];
    headerLabel.tag = section;
    headerLabel.userInteractionEnabled = YES;
    headerLabel.backgroundColor = [UIColor greenColor];
    headerLabel.text = [NSString stringWithFormat:@"Header No.%d",section];
    headerLabel.frame = CGRectMake(0, 0, tableView.tableHeaderView.frame.size.width, tableView.tableHeaderView.frame.size.height);


    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(catchHeaderGesture:)];
    tapGesture.cancelsTouchesInView = NO;
    [headerLabel addGestureRecognizer:tapGesture];

    return headerLabel;

    //return nil;
}

-(void)catchHeaderGesture:(UIGestureRecognizer*)sender
{
    UILabel *caughtLabel = (UILabel*)sender.view;

    NSLog(@"header no : %d", caughtLabel.tag);
}

I hope that helps.

Related Topic