Tinku
Tinku

Reputation: 133

Scrolling messes up custom cells in UITableView

I am developing an application which has a UITableView with custom UITableViewCells. The cells contain checkboxes and 3 labels. The user can select multiple rows by clicking on the checkboxes. When I select more than one row and scroll the table view, the checkmark vanishes from the checkbox. This means the selected rows are changed to unselected mode. How this can be fixed?

Upvotes: 0

Views: 994

Answers (2)

aopsfan
aopsfan

Reputation: 2441

I think your problem may be with cell reuse. Create an NSMutableDictionary in your controller (should be and instance variable), and create it like so:

dictionary = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                 [NSNumber numberWithBool:NO], [NSIndexPath indexPathForRow:0 inSection:0],
                 [NSNumber numberWithBool:NO], [NSIndexPath indexPathForRow:1 inSection:0], nil];

Do this for all your rows, or if needed, calculate the rows and their indexes, but set all their objects to [NSNumber numberWithBool:NO.

Now, in tableView:didSelectRowAtIndexPath:

if ([(NSNumber *)[dictionary objectForKey:indexPath] isEqualToNumber:[NSNumber numberWithBool:NO]) {
    [dictionary setObject:[NSNumber numberWithBool:YES] forKey:indexPath];
    // Do any visual updating necessary
} else {
    [dictionary setObject:[NSNumber numberWithBool:NO] forKey:indexPath];
    // Do any visual updating necessary
}

Now that we have a way of storing whether a cell is selected or not, change your cell identifier to work for your cells:

NSString *identifier = [[dictionary objectForKey:indexPath] stringValue];
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
}

// Do any visual updating necessary
return cell;

Now, update your custom cell class to accept @"0" and @"1" as identifiers, and update their selected state automatically based on this input.

Upvotes: 1

Shanti K
Shanti K

Reputation: 2918

I am guessing that this is because the cells are getting re-used. Which means that the cellForRowAtIndex: is called when the cell scrolls back into view. And the check box get defaulted to unselected mode. Store the state of the checkbox in an array and set the checkbox status of the cell as per that

Upvotes: 0

Related Questions