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

时间:2016-01-27 12:50:26

标签: ios objective-c uitableview uibutton

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

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

我在询问要使用的代理和数据源。

3 个答案:

答案 0 :(得分:1)

in

-(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];
   }

}

答案 1 :(得分:1)

从按钮

中删除所有操作
  [button removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];

为按钮添加操作

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

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

答案 2 :(得分:0)

tag值设置为button中的每个TableViewCell并添加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所选按钮,可根据需要自定义。