Reputation: 961
I'm trying to add a checkmark to a selected row and remove it when its selected again, but every time I select a row the checkmark only goes to the first cell and moves downwards after that (ie I click on any cell, then cell 0 has a checkmark, i click on any other cell, cell 1 has a checkmark, etc...).
Here's my didselectrowatindexpath and cellforrowatindexpath methods:
Update:
// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: @"preflabel"forIndexPath:indexPath];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"preflabel"];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
cell.textLabel.text = [NSString stringWithFormat:@"%@", data[indexPath.row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: @"preflabel"forIndexPath:indexPath];
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
Upvotes: 2
Views: 3995
Reputation: 2561
You have [tableView reloadData] this clears the curent state of your tableview.
Reloading the table view clears current state, including the current selection. However, if you explicitly call reloadData, it clears this state and any subsequent direct or indirect call to layoutSubviews does not trigger a reload.
For more information see.
Update
You are creating tableviewcells in the didSelectRowAtIndexPath and in cellForRowAtIndexPath. Why are you doing this? This will write over the cell that was selected.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
Upvotes: 4
Reputation: 79
you shouldn't get cell via deque method in the select method, because the cell you get is not the cell you touched,use cellForCellAtIndexPath like the deselect method:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryNone;
}
Upvotes: 2