I am trying to make this work but can't seem to wrap my mind around the idea.
So far I have it to where you are able to select a cell and it be able to produce a checkmark. Then, when you select a different cell, the previous checkmark would go away and the tableview would make a new checkmark on the new cell you just selected. This all works beautifully.
However, I am wanting to make it to where when you select the same cell with the checkmark, the checkmark does not disappear. But, it does!
I have tried numerous amounts of if statements to see if I can figure out how to make this work but can't figure out a solution. It is probably something minor that I need to rearrange in my code.
Here is my code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(self.checkedIndexPath)
{
UITableViewCell* uncheckCell = [tableView
cellForRowAtIndexPath:self.checkedIndexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
if([self.checkedIndexPath isEqual:indexPath])
{
self.checkedIndexPath = nil;
}
else
{
cellCheck = [tableView cellForRowAtIndexPath:indexPath];
cellCheck.accessoryType = UITableViewCellAccessoryCheckmark;
self.checkedIndexPath = indexPath;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSLog(@"%@", indexPath);
}
}
If you select the cell with checkmark, this code will be executed.
if(self.checkedIndexPath)
{
UITableViewCell* uncheckCell = [tableView
cellForRowAtIndexPath:self.checkedIndexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
This code will remove the checkmark which you have added during the first select.
then this code will be executed
if([self.checkedIndexPath isEqual:indexPath])
{
self.checkedIndexPath = nil;
}
Thus only when you select the same cell again, the checkmark will reappear
I think the cleaner way will be as followed.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* cellCheck = [tableView
cellForRowAtIndexPath:indexPath];
cellCheck.accessoryType = UITableViewCellAccessoryCheckmark;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* uncheckCell = [tableView
cellForRowAtIndexPath:indexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
AS you can get the value for self.checkedIndexPath from [tableView indexPathForSelectedRow]; the setting of self.checkedIndexPath is optional depending on the logic of your code.