Search code examples
iosobjective-cuitableviewaccessoryview

UITableView's AccessoryView Being Reused On Multiple Cells


I have a TableView that I would like to add a checkmark to a row when it is tapped. For that, I have:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

        NSString *selectedCountry = [self.files objectAtIndex:indexPath.row];
        NSString *Documents = [[NSBundle mainBundle] pathForResource:selectedCountry ofType:@"ppt" inDirectory:@"thepowerpoints"];
        //NSLog(@"%@", selectedCountry);
        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];

        if (newCell.accessoryType == UITableViewCellAccessoryNone) {
            if (self.chosen == nil) {
                self.chosen = [[NSMutableArray alloc] init];
            }
            newCell.accessoryType = UITableViewCellAccessoryCheckmark;
            [self.chosen addObject:Documents];
             NSLog(@"%@", self.chosen);

        }else {
            newCell.accessoryType = UITableViewCellAccessoryNone;
            [self.chosen removeObject:Documents];
        }

        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];


}

I understand that this is happening due to the dequeueReusableCellWithIdentifier on the type of Cell. My question is, what can I change, so that only the tapped rows get the checkmark, and not all of these other cells, once they start getting reused?


Solution

  • Move the code that decides whether a cell should be checked into cellForRowAtIndexPath. Keep a reference to the currently selected index/item and then set the checkmark on that cell. You would set unselected cells to have the accessory view set to none.