获取自定义单元格上的节号和行号按钮单击?

时间:2009-05-30 15:41:22

标签: iphone objective-c cocoa-touch

我有自定义单元格的tableview。表格分为多个部分和行。我在单元格上有一个自定义按钮。现在我想在点击该按钮时获得节号和行号。 关于这个的任何想法

5 个答案:

答案 0 :(得分:26)

您需要在视图控制器上实现UIControl事件处理方法,并将其设置为 all 按钮的处理程序。即在-tableView:cellForRowAtIndexPath:函数中,您可以执行以下操作:

[theCell.button addTarget: self
                   action: @selector(buttonPressed:withEvent:)
         forControlEvents: UIControlEventTouchUpInside];

然后您的事件处理程序将如下所示:

- (void) buttonPressed: (id) sender withEvent: (UIEvent *) event
{
    UITouch * touch = [[event touches] anyObject];
    CGPoint location = [touch locationInView: self.tableView];
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: location];

    /* indexPath contains the index of the row containing the button */
    /* do whatever it is you need to do with the row data now */
}

答案 1 :(得分:8)

一些想法:

您可以遍历按钮的超级视图层次结构,直到找到UITableViewCell,然后在UITableView上调用 - (NSIndexPath *)indexPathForCell:(UITableViewCell *)单元格。

- (void)buttonClicked:(id)sender {
  UIView *button = sender;

  for (UIView *parent = [button superview]; parent != nil; parent = [parent superview]) {
    if ([parent isKindOfClass: [UITableViewCell class]]) {
      UITableViewCell *cell = (UITableViewCell *) parent;           
      NSIndexPath *path = [self.tableView indexPathForCell: cell];

      // now use the index path

      break; // for
    }
  }
}

您也可以使用按钮的标记来存储引用该行的索引。这只包含一个整数,因此当您有一个部分时,或者当您将行作为一个平面列表进行管理时,它最有意义。

您可以替代地将UITableViewCell子类化以封装按钮。您的UITableViewCell可以响应按钮事件并将事件重新广播给自己的委托,传递自我。然后,事件委托可以在UITableView上调用 - (NSIndexPath *)indexPathForCell:(UITableViewCell *)单元格来获取索引路径。

答案 2 :(得分:6)

在tableView中选择单元格时会调用以下方法:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

访问部分编号:int section = indexPath.section;

访问行号(在正确的部分内):int row = indexPath.row;

答案 3 :(得分:2)

UITableView can convert a CGPoint coordinate into an indexPath

-(NSIndexPath *)indexPathForRowAtPoint:(CGPoint)point

答案 4 :(得分:1)

添加UITableViewCell子类的can实例变量要存储单元格的索引路径:

NSIndexPath *myIndexPath;

在以下位置创建单元格时:

cellForIndexPath:

将索引路径传递给新创建/回收的单元格。

现在当您按下按钮时,只需从您单元格的ivar中读取索引路径。

相关问题