【问题标题】:How to make a button on a table view cell call the correct tableView:cellForRowAtIndexPath?如何使表格视图单元格上的按钮调用正确的 tableView:cellForRowAtIndexPath?
【发布时间】:2012-09-26 02:13:42
【问题描述】:

我有一个按钮,它是自定义 UITableViewCell 的一部分。我想要的是当有人单击按钮时,为该单元格调用正确的 tableView:cellForRowAtIndexPath。

如何将按钮绑定到正确的 cellForRowAtIndexPath?

任何建议和/或代码示例都将受到高度赞赏

【问题讨论】:

    标签: ios uitableview


    【解决方案1】:

    您可以从触摸事件中获取 indexPath。将您的 buttonTapped 方法修改为:

    - (void) buttonTapped:(id) sender forEvent:(UIEvent *)event
    

    然后使用类似以下的内容:

    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:[[[event touchesForView:sender] anyObject] locationInView:tableView]];
    

    【讨论】:

      【解决方案2】:

      如果您只有一个部分,您可能可以使用UIViewtag 属性。

      理论上,类似下面的东西会起作用。

      - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)idxPath 
      {
          Your_UITableViewCell_Subclass * cell = [tableView dequeueCellWithIdentifier:@"..."];
          cell.button.tag = idxPath.row;
      
          ....
      
          return cell;
      }
      
      ....
      
      - (void) buttonTapped:(id) sender 
      {
          int idx = ((UIButton *)sender).tag;
          NSIndexPath * idxPath = [NSIndexPath indexPathForRow:idx inSection:0];
          UITableViewCell * cell = [self tableView:tableView cellForRowAtIndexPath:idxPath];
      
          // Do whatever you want to do with the cell
      }
      

      【讨论】:

      • 此解决方案不会处理多个部分。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多