【问题标题】:Identify the cell that was clicked - Beginner [duplicate]识别被点击的单元格 - 初学者 [重复]
【发布时间】:2015-05-26 01:44:51
【问题描述】:

我有一个 UITableView。有 5 行,每行有 4 个按钮。当用户点击按钮时,我想检索行 ID。

我使用UITapGestureRecognizer 来识别被选中的按钮。现在我想找到按钮所在的行。

我想使用 cell.myButton.tag =indexRow.row;。但是,我无法从ImageTapped 方法接收它。有人可以帮我吗 ?

以下代码是cellForRowAtIndexPath 的一部分 cellForRowAtIndexPath

UITapGestureRecognizer *tap = nil;

            tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ImageTapped:)];

            [cell.myButton addGestureRecognizer:tap];

...对于另一个按钮也是如此。

ImageTapped方法

- (void) ImageTapped:(UITapGestureRecognizer *) recognizer {
    if(recognizer.state == UIGestureRecognizerStateEnded)
    {

    }
}

【问题讨论】:

  • @iphonic : TapGesture 不适用于 UIButtons,谁告诉你的?
  • @iphonic : 我尝试并使用 TapGesture 来查找 UIButton 上的双击。 example
  • @FahimParkar Applogies 先生,它确实有效,我有不同的想法,感谢您的澄清..

标签: ios objective-c


【解决方案1】:

首先你为什么要使用手势并且不需要添加手势。你可以使用addTarget 方法来做这件事。

在这个方法cellForRowAtIndexPath:

myButton.tag = indexPath.row;
[myButton addTarget:self action:@selector(ImageTapped:) forControlEvents:UIControlEventTouchUpInside];

你可以通过这个方法获得:

- (void) ImageTapped:(id) sender {
    int rowId = [(UIButton *)sender tag];
}

否则你可以得到这样的:

cell.myButton.tag = indexPath.row;// In cellForRowAtIndexPath Method

- (void) ImageTapped:(UITapGestureRecognizer *) recognizer {

    if(recognizer.state == UIGestureRecognizerStateEnded)
    {
        int rowId = recognizer.view.tag;  
    }

}

【讨论】:

    【解决方案2】:

    按钮将是单元格的后代子级。因此您可以使用以下代码获取单元格:

    id view;
    while (![(view = button.superView)  isKindOfClass:[UITableViewCell class]]) ;
    // now view will be the parent cell.
    

    【讨论】:

    • ... 然后使用 indexPathOfCell 获取单元格的索引路径。这比获取标签要好得多,因为即使行已重新排列,它也会为您提供 indexPath,因此这是一个可扩展的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2015-02-11
    相关资源
    最近更新 更多