Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
Gaurav_soni Avatar asked Mar 16 '12 10:03

Gaurav_soni


People also ask

What is UITapGestureRecognizer Swift?

UITapGestureRecognizer is a concrete subclass of UIGestureRecognizer . For gesture recognition, the specified number of fingers must tap the view a specified number of times. Although taps are discrete gestures, they're discrete for each state of the gesture recognizer.


1 Answers

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;
    // ...
}
like image 51
sch Avatar answered Nov 12 '22 11:11

sch