【问题标题】:How to write actions for UIButton placed in every cell of tableview? [duplicate]如何为放置在 tableview 的每个单元格中的 UIButton 编写动作? [复制]
【发布时间】:2013-12-29 08:51:30
【问题描述】:

我有一个自定义表格视图单元格,其中有一个 UIButton。 我想为放置在 tableview 单元格中的每个按钮编写动作。告诉我怎么做。 我曾尝试使用标签,但它不能作为 cellForRowAtIndexPath 一次加载所有单元格,因此它会覆盖标签号。 请告诉我该怎么做。 我正在使用以下代码

if(indexPath.row == 0){[cell.viewButton addTarget:self action:@selector(playMovie) forControlEvents:UIControlEventTouchUpInside];
       cell.viewButton.tag = 1;
    }
    else {
        [cell.viewButton addTarget:self action:@selector(playMovie) forControlEvents:UIControlEventTouchUpInside];
        cell.viewButton.tag = 2;
    }
return cell;

【问题讨论】:

  • 你想对不同的按钮做不同的操作还是对所有按钮做相同的操作
  • 不同按钮的不同操作,我不想使用 didSelectRowAtIndexPath。
  • @jrturton 它不重复。我的问题中的 PFP 已更新。我没有使用 IBOutlet,它只是一个 UIButton。
  • 它是重复的。无论您是否使用插座,都没有区别。您想知道单击按钮时该按钮在哪个单元格中,对吧?

标签: ios iphone uitableview uibutton


【解决方案1】:

您可以给按钮添加按钮标签,然后您可以在其方法中识别该按钮。

cell.btn.tag = indexPath.row+1;

你可以在它的点击事件中得到它

-(void)btnOnClick:(id)sender
{
UIButton *btnTag = (UIButton *)sender.tag;
if(btn.tag == 1)
{
}
}

【讨论】:

  • 为什么要加+1?他们有什么特殊原因吗?
  • in tableview indexPath.row 以 0 开头,这就是为什么添加 +1 所以它以 +1 开头。没有别的了。
  • 是的,我能理解你的所作所为。但是即使您不添加 +1,代码也应该可以工作.. 这就是为什么问.. 快乐编码:)
  • 是的,我知道你在点击事件中将标签与 0 进行比较...
【解决方案2】:

也使用@selector 传递按钮实例

[cell.viewButton addTarget:self action:@selector(playMovie:) forControlEvents:UIControlEventTouchUpInside]
cell.viewButton.tag = indexpath.row;

然后像这样实现按钮点击方法

-(void)playMovie:(UIButton *)sender{

  if(sender.tag == 0){
  NSLog(@"button at first cell");

  }else if (sender.tag  == 1){
  NSLog(@"button at first cell");
  }
  // SO on.......
}

【讨论】:

    【解决方案3】:

    No need to add target for every rows,做这样的事情:

    if(indexPath.row == 0){
           cell.viewButton.tag = 100;
        }
        else {
            cell.viewButton.tag = 101;
        }
    [cell.viewButton addTarget:self action:@selector(playMovie:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
    
    
    -(IBAction)playMovie:(id)sender{
    if(sender.tag == 100){
    // Do your Stuff..
    }else if(....).....
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 2011-10-27
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      相关资源
      最近更新 更多