1
votes

What is the best way Add and remove target actions for UIButton in UITableViewCell.

For each row of the I will have different button action based on the row index. Show please tell me where do I add the add target for button and remove target for the button.

I am asking about the delegate and data source to be used.

3
simply add target at the time when you are adding button on table cell & set button tag as index path of the row. Now receive this button tag in target method & apply action corresponding to button tag.Gagan_iOS
Yes it is simple implement and in my implementation i won't have same logic to use index path. The action methods differs based on row index.Arasuvel
then add one single function in button action in -cellForRowAtIndexPath: method and get button tag for selected index of row . and perform action based on tag(indexpath)Bhargav B. Bajani

3 Answers

3
votes

Remove all the actions from the button

  [button removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];

Add an action for the button

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

Notice that if you switch the button from one action to another action due to status change, it is good to remove the actions. Otherwise, all the actions can show up even you reloadData for the table.

1
votes

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

}
0
votes

Set tag value to each button in TableViewCell and add target also as shown below..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  cell.btn.tag = indexPath.row;
  [btn addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
  return cell;
}

Now add a selector method btnTapped like shown below. This method calls every time for each button click event in tableview cell.

- (void)btnTapped:(UIButton *)sender {
   UITableViewCell * cell = [[sender superview] superview];
   NSIndexPath * path = [self.tableView indexPathForCell:cell];
}

Here you have indexpath of the selected button, customise however you want.