-3

i am having a custom tableview cell where i have a UIButton. i want to write action for every button placed in tableview cell. tell me how to do it. i have tried using tag but its not working as cellForRowAtIndexPath load all the cell at once so its overwriting the tag number. please tell me how to do it. following code i am using

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;

enter image description here

Deepak Carpenter
  • 1,504
  • 2
  • 10
  • 21

3 Answers3

1

Pass the instance of button also with @selector

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

And then implement the button click method like this

-(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.......
}
Gyanendra Singh
  • 1,483
  • 12
  • 15
1

You can give button tag to your button then you can identified that button in its method.

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

and you can get that in its click event

-(void)btnOnClick:(id)sender
{
UIButton *btnTag = (UIButton *)sender.tag;
if(btn.tag == 1)
{
}
}
Maulik Kundaliya
  • 452
  • 3
  • 17
0

No need to add target for every rows, Do something like this :

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(....).....

}
Kumar KL
  • 15,315
  • 9
  • 38
  • 60