1

I created one prototype cell. Cell has one label and one button. I have given tag's for both. Now i want to detect which button is clicked from 10 cells.

Previously we were differentiating that based on tag. But how to do this with prototype cell.

My code for cell creation is as follows:

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cellIdentifier"];
    }

    UIButton *stopStartButton = (UIButton *)[cell viewWithTag:103];
    UILabel *chargingLabel = (UILabel *)[cell viewWithTag:102];
}


-(IBAction)stopStartButtonClicked:(id)sender
{
  NSLog(@"Button clicked");
}
Rakesh
  • 1,177
  • 1
  • 15
  • 31

2 Answers2

1

You can use button.titleLabel.tag for differentiate your button and at action time you can compare with same tag.

second option is with your button action. you can append event so that is also provide you all information regarding your button.

For example you just set

stopStartButton.titleLabel.tag=1;

-(IBAction)stopStartButtonClicked:(id)sender
{
     NSLog(@"Button clicked %d",sender.titleLabel.tag);
}
ChintaN -Maddy- Ramani
  • 5,156
  • 1
  • 27
  • 48
Tamnna
  • 250
  • 2
  • 10
  • This will cause intermittent crashes when cells are re-used. If you want to have button actions please see this answer: http://stackoverflow.com/questions/21355612/custom-uitableviewcell-button-selected-reload-data/21355661#21355661 – CW0007007 Nov 13 '14 at 08:27
0

I think the best way is to find what cell does actually has button that was tapped. You can find it by calculating x origin point of button.

- (IBAction)stopStartButtonClicked:(id)sender
{
  CGPoint pointInTable = [button convertPoint:button.bounds.origin toView:self.tableView];
  NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInTable];
}

If you have indexPath, you can get cell:

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
Artem Loginov
  • 801
  • 7
  • 8