views:

1970

answers:

1

Hi

I am using a custom UITableViewCell class. My cell has multiple buttons (4 to be precise) on it and the button clicks are handled in the UIViewController which uses this cell class.

I was trying to use the button's tag to calculate the row number on which the button was clicked. But doing this causes an issue if a cell was not created and instead uses a free object. In that case the tag and the row number do not match.

Can someone please tell me how I can handle this case? If I give the same tag to all buttons in different rows, how can I identify the row on which the button was clicked?

Thanks a lot.

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

    static NSString *CellIdentifier = @"Cell";

    MyTableCell *cell = (MyTableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {   
     // whatever you have now
    }
    // Set up the cell...
    cell.myListViewController = self;
    int tag = indexPath.row;
    cell.button1.tag = tag;
    cell.button2.tag = tag;
    cell.button3.tag = tag;
....
}

This code will have a unique tag for buttons in each row. You are setting the tag not in the new cell creation but for all cases, including reuse.

mahboudz
So you're saying I retain the instances of UIButton objects in the UITableViewCell class?
lostInTransit
Note that using the row as the tag will only work reliably if you have one table section.
Alex Reynolds
Yes, I just have one section. Thanks.
lostInTransit
Yes you're buttons will get reused. Right now, I assume you create them inside the if (cell == nil) {} and since they are added to the subview, they are retained. So they should be available to use as above. If you want, you can test this by setting the title of a button to the row number in a similar way as above and just see how it works. The button will change names to state the correct row number.
mahboudz