iOS: How to keep selected/check marked cells in UITableView to stay after navigating back and forth in UINavigationController?

StackOverflow https://stackoverflow.com/questions/13537495

Вопрос

I have tab bar in which one tab has a UINavigationController that is assigned a root view controller which consists of a UITableView that drills down to more choices. After i select an item in my root view controller i am given another uitableview and i use the following to assign only one checkmark to that section or group using the following code in my cellForRowAtIndexPath.

if([self.checkedIndexPath isEqual:indexPath])
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
    cell.accessoryType = UITableViewCellAccessoryNone;
}

and the following in didSelectRowAtIndexPath:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Uncheck the previous checked row
if(self.checkedIndexPath)
{
    UITableViewCell* uncheckCell = [tableView
                                    cellForRowAtIndexPath:self.checkedIndexPath];
    uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
self.checkedIndexPath = indexPath;

[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

My Problem is that when i use the back button on my navigation menu and go back to the same UItableview, the checkmark disappears. however this is not the case when i scroll up and down in that view. How do i keep those checkmarks there when i go back and forth using my navigation controller.

Это было полезно?

Решение

I believe you're having this issue because you are pushing a new UIViewController instance whenever you go back and forth - the new instance doesn't know what the previous checkedPath property was.

To solve this you need to either:

  1. Persist the checked row value somehow (NSUserDefaults, CoreData, etc..). This way any instance would get the same checked row value
  2. Re-use the same view controller when pushing.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top