views:

27

answers:

1

hello,

I have this code on my cellForRowAtindexPath, with a custom cell and a button on the each cell.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
 static NSString *MyIdentifier = @"tblCellView";

 TableCellView *cell = (TableCellView *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];

 Alarms *alarma = (Alarms *)[alarmsArray objectAtIndex: indexPath.row];

 if (!cell) {
  [[NSBundle mainBundle] loadNibNamed:@"TableCellView" owner:self options:nil];
  cell = tblCell;

  UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(-7, 4, 30, 33)];

  [button addTarget:self action:@selector(favButtonAction:) forControlEvents:UIControlEventTouchUpInside];
  [button setTag:1];
  [cell.contentView addSubview:button];

  [button release];
 }

 // Set up the cell.
 [cell setLabelText:  [alarma nombreAlarma]];

 UIButton *button = (UIButton *)[cell viewWithTag:1];

 button.tag = indexPath.row;

 return cell;
}

My problem is that when I click on the button, I got random results, as soon as I move on the table and cells are reusing I got different indexes that are not equal to label tex for the cell in question.


-(IBAction)favButtonAction: (id)sender
{
 UIButton *button = (UIButton *)sender; 

 Alarms *alarma = (Alarms *)[alarmsArray objectAtIndex: button.tag];

 NSLog(@"labelText: %@",[alarma nombreAlarma]);

}

for example, the first cell always is ok but the last cell is equal to first objectAtIndex (maybe button.tag is equal to 0 when it must be 14?)

A: 

Ok I found a solution, is a different approach but it works :

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

and then on the button handler:

- (void)checkButtonTapped:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
    if (indexPath != nil)
    {
     ...
    }
}

more info here http://stackoverflow.com/questions/1802707/detecting-which-uibutton-was-pressed-in-a-uitableview

david