如何在UITapGestureRecognizer的@selector中传递参数?

7

我在表头视图部分有以下内容:

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

我希望能在sectionHeaderTapped方法中传递段落编号,以便可以识别点击的是哪个段落。

我的方法实现看起来像这样:

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

我该如何实现这个目标?
2个回答

15

sectionHeaderTapped 方法应该具有以下签名之一:

- (void)sectionHeaderTapped:(UITapGestureRecognizer *)sender;
- (void)sectionHeaderTapped;
你需要使用点击的坐标来确定被点击的单元格。
-(void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer
{
    CGPoint tapLocation = [gestureRecognizer locationInView:self.tableView];
    NSIndexPath *tapIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation];
    UITableViewCell* tappedCell = [self.tableView cellForRowAtIndexPath:tapIndexPath];
}

使用那种方法可能可以获取到部分标题。但是,将不同的手势识别器附加到每个章节标题可能会更容易。

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

然后

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

是的,我已经为每个部分使用了不同的手势,虽然这不是最好的方法,但更容易...谢谢。 - Gaurav_soni

0
一个替代方案:您可以在tableHeaderView上添加UIButton并获取按钮的点击。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接