在UITableView中单击UIButton会单击多个按钮

时间:2014-08-10 21:17:55

标签: ios objective-c uitableview

当我在UItableView中选择一个按钮时,也会点击下方的其他按钮。我在自定义tableview中的按钮上使用目标操作,并在方法中更改发件人的标题。为什么单击一个按钮选择多个UIButtons?任何帮助/建议将不胜感激。

编辑:我正在使用分段的tableview

这是我的代码:

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

    PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    // Configure the cell...
    [cell.likeButton addTarget:self action:@selector(likeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    cell.likeButton.tag = indexPath.section;
    return cell;
}

-(void)likeButtonPressed:(UIButton *)sender {
    NSLog(@"%d",sender.tag);
    [sender setTitle:@"Pressed" forState:UIControlStateNormal];
}

3 个答案:

答案 0 :(得分:1)

在PostTableViewCell.h中定义一个委托

@protocol HandleCellInteractionDelegate <NSObject>
-(void) didPressButton:(NSString*)action forCell:(UITableViewCell *)theCell;
@end

在TableView.h中注册为此协议的委托

<HandleCellInteractionDelegate>

在TableView.m文件中添加委托处理程序

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // Create cell
    ....
    cell.delegate = self;
    if (self.qObjects current object's selection state == selected)
        enable button
    else
        disable button
 }

添加协议功能     #pragma mark HandleCellInteractionDelegate

-(void) didPressButton:(NSString*)action forCell:(UITableViewCell *)theCell{
    // Now here you have access to your cell again. And you can update the cell's button text as needed
    // Here save selection state in data model.. in self.qObjects <==
    cell.questionTextView.text = @"bla bla";

}

答案 1 :(得分:0)

在你的uitableviewcell子类中,确保在init期间只向单元格添加一个按钮。否则,每次tableviewcontroller调用dequeueReusableCellWithIdentifier时,您都会向单元格添加一个额外的按钮。

试试这个: //将属性添加到自定义单元格以保存indexPath

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

      PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

      // Configure the cell...
      cell.indexPath = indexPath;
      return cell;
   }

在你的细胞子类中连接一个动作方法,如下所示:

  - (IBAction)buttonAction:(id)sender {

    NSLog(@"indexPath: %@", self.indexPath);
  }

答案 2 :(得分:0)

我认为你在一个部分中有多行,所以该部分的所有按钮都被选中 使用  cell.likeButton.tag = indexPath.row; 代替   cell.likeButton.tag = indexPath.section;