views:

55

answers:

2

Hi,

I am trying to have a button for selected rows of my table.

Here is the example code I am using:

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

    static NSString *ControlRowIdentifier = @"ControlRowIdentifier";

    UITableViewCell *cell = [tableView 
                             dequeueReusableCellWithIdentifier:ControlRowIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                       reuseIdentifier:ControlRowIdentifier] autorelease];
    }

    if ([indexPath row] > 5) {

        UIImage *buttonUpImage = [UIImage imageNamed:@"button_up.png"];
        UIImage *buttonDownImage = [UIImage imageNamed:@"button_down.png"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0.0, 0.0, buttonUpImage.size.width, buttonUpImage.size.height);
        [button setBackgroundImage:buttonUpImage forState:UIControlStateNormal];
        [button setBackgroundImage:buttonDownImage forState:UIControlStateHighlighted];
        [button setTitle:@"Tap" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = button;

    }

    NSUInteger row = [indexPath row];
    NSString *rowTitle = [list objectAtIndex:row];
    cell.textLabel.text = rowTitle;

    return cell;
} 

This code works absolutely fine when loaded for 1st time. So, as per the logic it shows 'Tap' button for all rows greater than 5.

Problem occurs when I scroll up and down. Once I do that it just starts putting that button at any random row. I dont understand why it does that and it'll be really helpful if someone can give some tips on this.

Thanks.

+1  A: 

The problem is reusing cell's identifier. In your case, the cell with an index of less than 6 must be with one identifier, and the rest from other.

Victor
Thanks Victor! The problem was indeed with reusage of the cell's identifier. Once I used unique identifier, the problem was gone!
Unique identifier need for a cells with unique characteristics, in your case is the cell with a button and a cell without a button. If for each cell generate unique identifier they will stop reusing that will affect efficiency
Victor
A: 

Table view cells is reusable objects and you must do some clean work with it. Try use next:

if ([indexPath row] > 5) {

    ...


} else {
    cell.accessoryView = nil;
}
Skie