处理来自原型 UITableViewCell 的操作

Handle actions from prototype UITableViewCell

我有一个带有 3 个按钮的原型 UITableViewCell,我将它们称为按钮 1、按钮 2 和按钮 3。

举例来说,我将 2 个项目的数组加载到我的 UITableView 中,因此这个原型 UITableViewCell 的 2 个实例,每个实例都有 3 个按钮;如何处理这些按钮的操作并确定在哪一行点击了哪个按钮。

更新

使用下面的代码,该行始终为 0...有什么想法吗?

ParentDashboardChildTableViewCell *cell = (ParentDashboardChildTableViewCell *)[sender superview].superview;
    NSIndexPath *indexPath = [self.overviewTableView indexPathForCell:cell];
    NSLog(@"selected tableview row is %ld", (long)indexPath.row);

您可以为每个按钮使用标签。对于 reference

为 table 单元格上的三个按钮分配标签值。您可以按以下格式分配标签值:00,01,02,以便 o 指行号,1,2,3 指按钮。

      NSString *tagString_for_Button1=[NSString stringwithformat:@"%d%d"indexPath.row,1];
         NSString *tagString_for_Button2=[NSString stringwithformat:@"%d%d"indexPath.row,2];
            NSString *tagString_for_Button3=[NSString stringwithformat:@"%d%d"indexPath.row,3];
        cell.yourbutton1.tag = [tagString_for_Button1 integerValue];
         cell.yourbutton2.tag = [tagString_for_Button2 integerValue];                    
           cell.yourbutton3.tag = [tagString_for_Button3 integerValue];

并将目标操作添加到您的按钮,如下所示:

    [cell.yourbutton1 addTarget:self action:@selector(yourButtonClicked1:) forControlEvents:UIControlEventTouchUpInside];
    [cell.yourbutton2 addTarget:self action:@selector(yourButtonClicked2:) forControlEvents:UIControlEventTouchUpInside];
    [cell.yourbutton3 addTarget:self action:@selector(yourButtonClicked3:) forControlEvents:UIControlEventTouchUpInside];

 and define the methods for those buttons based on index as follows:
     -(void)yourButtonClicked:(UIButton*)sender
   {
 if (sender.tag == 0) 
 {
 //Here your coding.

 }
 }

假设您已经将按钮的目标操作定义为一个名为 "actionCellButtonClicked" 的方法,那么您可以像那样实现该方法

-(IBAction)actionCellButtonClicked:(id)sender {
    CustomCollectionCell *cell = (CustomCollectionCell *) [sender superview];
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    // to do somthing
 }

注意:[sender superview] 它允许遍历包含您的按钮的视图层次结构。换句话说,您获得了单元格,然后您可以获得单元格的索引。我使用了 collectionView,但是 table 视图有一个等效的方法。