i'm trying to do a selection list in UITableView but whenever i tap in a row, two row are marked. For example if i tap the first row it adds a checkmark to row = 0 and row = 11. I think the problem is caused by reuse of cells but i don't understand how solve it.
I attach my code .h:
@interface tabellaViewController : UITableViewController
@property (nonatomic, strong) NSArray *listaingredienti;
@end
and my code .m:
- (void)viewDidLoad
{
[super viewDidLoad];
_listaingredienti = [NSArray arrayWithObjects:@"formaggio", @"crudo", @"pomodorini", @"fossa", @"bresaola", @"funghi", @"salame", @"fontina", @"rucola", @"radicchio", @"peperoni", @"ciccioli", @"squacquerone", @"gorgonzola", @"salsiccia", @"cipolla", @"feta", @"acciughe", @"pecorino", nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_listaingredienti count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [_listaingredienti objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow]
animated:NO];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
I've seen UITableView didSelectRowAtIndexPath add additional checkmark at tap where there is a similar post but i already use dequeueReusableCellWithIdentifier:CellIdentifier.
Anyone can help me?
Ok, i'm just solved my question. Actually, the problem was in reuse of cells, but this code fix it.
Just replace in cellForRowAtIndexPath::
static NSString *CellIdentifier = @"Cell";
with:
NSString *CellIdentifier = [NSString stringWithFormat:@"MyReuseIdentifier %d",indexPath.row];