I have a very simple UITableViewController
subclass designed to show users the characters in the alphabet in cells. When the user presses on a cell, it is to set its accessory type to a checkmark.
#import "MTGTableViewController.h"
@interface MTGTableViewController ()
@property (nonatomic, strong) NSArray *data;
@end
@implementation MTGTableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_data = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = _data[indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
@end
The table view works fine. I have my reuseIdentifier property set in the storyboard on my prototype cells, and it all looks good before I start selecting cells.
The problem: When I select any cell, say the "A" cell, other not-yet-visible cells are also given checkmarks when i scroll down to them. Even worse, when I scroll up and down, sometimes the checkmark on cell "A" is removed and given to cell "B".
I had this problem a little while ago as well, you need to add another array that keeps track of the which cell are marked. Just make an array of NSIndexPaths that are the ones marked. Sort of like:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if ([arrayOfMarked containsObject:indexPath]) {
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}