检测UITableView中按下了哪个UIButton

  • 问题:
  • 我有一个包含5个UITableViewCells的UITableView。每个单元格包含一个ui按钮,设置如下:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
    cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    [cell autorelelase];

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
    [button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
    [button setTag:1];
    [cell.contentView addSubview:button];

    [button release];
    }

    UIButton *button = (UIButton *)[cell viewWithTag:1];
    [button setTitle:@"Edit" forState:UIControlStateNormal];

    return cell;
    }

    我的问题是:在buttonPressedAction:方法中,我如何知道哪个按钮被按下了。我考虑过使用标签,但我不确定这是最好的路线。我希望能够以某种方式将indexath标记到控件上

    - (void)buttonPressedAction:(id)sender
    {
    UIButton *button = (UIButton *)sender;
    // how do I know which button sent this message?
    // processing button press for this row requires an indexPath.
    }

    标准的做法是什么?在

    编辑:

    我通过以下几点解决了这个问题。我仍然想知道这是标准的做法还是更好的办法?在

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
    cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    [cell autorelelase];

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
    [button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:button];

    [button release];
    }

    UIButton *button = (UIButton *)[cell.contentView.subviews objectAtIndex:0];
    [button setTag:indexPath.row];
    [button setTitle:@"Edit" forState:UIControlStateNormal];

    return cell;
    }

    - (void)buttonPressedAction:(id)sender
    {
    UIButton *button = (UIButton *)sender;
    int row = button.tag;
    }

    需要注意的是,我不能在创建单元时设置标记,因为单元可能会退出队列。感觉很脏。一定有更好的办法

  • 答案:
  • 在苹果的Accessory使用以下方法取样:

    [button addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

    然后在触摸处理程序中检索触摸坐标,并根据该坐标计算索引路径:

    - (void)checkButtonTapped:(id)sender
    {
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
    if (indexPath != nil)
    {
    ...
    }
    }