在 UITableViewCell 中为 UIButton 添加和删除目标操作

Posted

技术标签:

【中文标题】在 UITableViewCell 中为 UIButton 添加和删除目标操作【英文标题】:Add and remove target actions for UIButton in UITableViewCell 【发布时间】:2016-01-27 12:50:25 【问题描述】:

的最佳方法是什么。

对于每一行,我将根据行索引有不同的按钮操作。请告诉我在哪里添加按钮的添加目标和删除按钮的目标。

我在询问要使用的委托和数据源。

【问题讨论】:

在表格单元格上添加按钮并将按钮标签设置为行的索引路径时只需添加目标。现在在目标方法中接收此按钮标签并应用与按钮标签对应的操作。 是的,它是简单的实现,在我的实现中我不会有相同的逻辑来使用索引路径。操作方法因行索引而异。 然后在 -cellForRowAtIndexPath: 方法中的按钮操作中添加一个函数并获取所选行索引的按钮标记。并根据 tag(indexpath) 执行操作 【参考方案1】:

移除按钮的所有动作

  [button removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];

为按钮添加一个动作

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

请注意,如果由于状态更改而将按钮从一个动作切换到另一个动作,最好删除这些动作。否则,即使您为表格重新加载数据,所有操作也会显示出来。

【讨论】:

【参考方案2】:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    [cell.btn1 removeTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside];
    [cell.btn1 removeTarget:self action:@selector(action2:) forControlEvents:UIControlEventTouchUpInside];

    cell.btn1.tag = indexPath.row;

   if(indexPath.row%2)
   
        [cell.btn1 addTarget:self action:@selector(onbtnWeighIn:) forControlEvents:UIControlEventTouchUpInside];
   
   else
        [cell.btn1 addTarget:self action:@selector(onBtnViewTable:) forControlEvents:UIControlEventTouchUpInside];
   


【讨论】:

谢谢。对上述代码的小更新 [cell.btn1 removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];。我只做了上述,但这是否是最好的方法?【参考方案3】:

tag值设置为TableViewCell中的每个button,并添加target,如下所示..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
  cell.btn.tag = indexPath.row;
  [btn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
  return cell;

现在添加一个选择器方法btnTapped,如下所示。每次在tableview单元格中的每个按钮单击事件都会调用此方法。

- (void)btnTapped:(UIButton *)sender 
   UITableViewCell * cell = [[sender superview] superview];
   NSIndexPath * path = [self.tableView indexPathForCell:cell];

这里有所选按钮的indexpath,随意自定义。

【讨论】:

以上是关于在 UITableViewCell 中为 UIButton 添加和删除目标操作的主要内容,如果未能解决你的问题,请参考以下文章

在 UITableViewCell 中为 UITableView 设置动画

为啥我的自定义 UITableViewCell 在 cellForRowAtIndexPath 中为空?

在 UITableViewCell 中为自定义 UIButton 设置动画

无法在 UITableViewCell 中为 UIImageView 设置图像大小

如何在默认样式的 UITableViewCell 中为我还没有的图像保留空间

在 UITableViewCell 中为 UIButton 添加和删除目标操作