【问题标题】:UITableViewCell Checkmark - How to save and retrieve indexPath?UITableViewCell 复选标记 - 如何保存和检索 indexPath?
【发布时间】:2014-12-09 21:36:33
【问题描述】:

previous SO question 之后,我试图通过保存和其他内容正确选择 tableView 单元格。

我已将其切换,但无法保存 indexPath 并检索它以显示选择,即使用户离开视图或重新启动应用程序也是如此。

代码如下:

@property (nonatomic, strong) NSIndexPath* lastIndexPath;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

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


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if(self.lastIndexPath)
    {
        UITableViewCell* uncheckCell = [tableView
                                        cellForRowAtIndexPath:self.lastIndexPath];
        uncheckCell.accessoryType = UITableViewCellAccessoryNone;
    }
    if([self.lastIndexPath isEqual:indexPath])
    {
        self.lastIndexPath = nil;
    }
    else
    {
        UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        self.lastIndexPath = indexPath;
    }


    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSNumber numberWithInt:self.lastIndexPath.row] forKey:@"selectedCell"];
    [defaults synchronize];

}

即使在用户关闭并重新打开视图后,如何保存 indexPath 并检索它以显示选择?

提前致谢。

【问题讨论】:

  • 如果只需要单选,则不需要selArray。只需跟踪选定的索引路径。
  • 我试过了,但我无法保存 indexPath 并检索检查状态。

标签: ios objective-c uitableview


【解决方案1】:

您应该在viewWillAppear 中添加此内容。

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber *lastRow = [defaults objectForKey:@"selectedCell"];
if (lastRow) {
    self.lastIndexPath = [NSIndexPath indexPathForRow:lastRow.integerValue inSection:0];
}

重启应用时,应该从NSUserDefaults获取lastIndexPath,否则为nil。

【讨论】:

  • 非常感谢!工作完美。我可以在 12 小时内提供赏金
【解决方案2】:

你应该做两件事:

1) 在 didSelectRowAtIndexPath 中,如果之前选中的行可见,则重新加载它 2) 在 cellForRowAtIndexPath 中,检查 indexpath.row 是否与您选择的单元格相同。如果是,请给它打勾,如果不是,请不要

【讨论】:

  • 选中一行时不需要重新加载表格视图。如果之前选择的行可见,只需重新加载它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
相关资源
最近更新 更多