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

在 UITableViewCell 中为 UIButton 添加和删除目标操作的最佳方法是什么。

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

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

【问题讨论】:

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

标签: ios objective-c uitableview uibutton


【解决方案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,随意自定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      相关资源
      最近更新 更多