Gaurav_soni
Gaurav_soni

Reputation: 6114

How to pass argument in @selector in UITapGestureRecognizer?

I have this in my table header view section:

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(sectionHeaderTapped:)];

I want to pass the section number in the method sectionHeaderTapped so i can recognize which section got tapped.

My method implementation looks like this:

-(void)sectionHeaderTapped:(NSInteger)sectionValue {
    NSLog(@"the section header is tapped ");    
}

How can I achieve this?

Upvotes: 7

Views: 7045

Answers (2)

sch
sch

Reputation: 27536

The method sectionHeaderTapped should have one of the following signatures:

- (void)sectionHeaderTapped:(UITapGestureRecognizer *)sender;
- (void)sectionHeaderTapped;

You have to figure out the cell that was tapped using the coordinates of the tap.

-(void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer
{
    CGPoint tapLocation = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *tapIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation];
    UITableViewCell* tappedCell = [self.tableView cellForRowAtIndexPath:tapIndexPath];
}

You can probably get the section header using that method. But it may be easier to attach a different gesture recognizer to each section header.

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    // ...
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(sectionHeaderTapped:)];
    [headerView addGestureRecognizer:tapGesture];
    return headerView;
}

And then

-(void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer
{
    UIView *headerView = gestureRecognizer.view;
    // ...
}

Upvotes: 15

Maulik
Maulik

Reputation: 19418

An alternate : You can add UIButton on the tableHeaderView and get click of button.

Upvotes: 0

Related Questions