Ios 将UITableView中的选定行保存为NSUserDefaults

Ios 将UITableView中的选定行保存为NSUserDefaults,ios,swift,uitableview,Ios,Swift,Uitableview,我正在尝试保存行的选定状态,以便在tableview加载时显示选定行的相应复选标记。我在viewDidAppear中尝试了下面的方法,但它不起作用 override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) let checkMarkToDisplay = NSUserDefaults.standardUserDefaults().valueForKey("lastSelection") as! Int las

我正在尝试保存行的选定状态,以便在tableview加载时显示选定行的相应复选标记。我在viewDidAppear中尝试了下面的方法,但它不起作用

override func viewDidAppear(animated: Bool) {

super.viewDidAppear(true)
let checkMarkToDisplay = NSUserDefaults.standardUserDefaults().valueForKey("lastSelection") as! Int
lastSelection = NSIndexPath(forRow: checkMarkToDisplay, inSection: 0)
self.tableView.cellForRowAtIndexPath(lastSelection)?.accessoryType = .Checkmark

}

var lastSelection: NSIndexPath!

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

if self.lastSelection != nil
{

    self.tableView.cellForRowAtIndexPath(self.lastSelection)?.accessoryType = .None
}

if indexPath.row > 0
{
    self.tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark

    self.lastSelection = indexPath

    self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}      

NSUserDefaults.standardUserDefaults().setObject(indexPath.row, forKey: "lastSelection")

请在cellForRowAtIndexPath中实现您的逻辑,并从ViewDidDisplay中删除您的复选标记代码

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let checkMarkToDisplay  =   NSUserDefaults.standardUserDefaults().valueForKey("lastSelection") as! Int

    if checkMarkToDisplay == indexPath.row{
        cell?.accessoryType = .Checkmark
    }
    else{
        cell?.accessoryType = .None
    }
}
将其移动到viewDidLoad()

删除这个

self.tableView.cellForRowAtIndexPath(lastSelection)?.accessoryType = .Checkmark
然后将此添加到

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //create the cell
    //then
    cell.accessoryType = lastSelection == indexPath ? .Checkmark : .None

    //other cell configuration

    return cell
}

cellforrowatinexpath
delegate方法中执行此检查,而不是将出现
view
。如果(indexath.row==NSUserDefaults.standardUserDefaults().valueForKey(“lastSelection”)为!Int),则在其上设置一个检查条件
if
。然后在ViewDidDisplay期间设置附件类型,不知道目标单元格是否已经创建。您必须在tableView委托方法中执行单元格自定义操作。现在,这是有意义的。感谢您的澄清,如果他已经在cellForRowAtIndexPath中,为什么他必须创建indexPath?只需检查indexPath.row是否等于要显示的复选标记,然后设置辅助复选标记。当您已经在中时,无需创建indexpath或调用CellForRowatineXpath方法there@NSNoob是的,我已经按照他的要求执行了,就像他想要的一样。好的,太好了。如果你能解释一下他在代码上犯了什么错误,那会很有帮助。我留下了一条评论,但人们最有可能看到答案。这正是原因,我们不能在评论框上放太多的行。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    //create the cell
    //then
    cell.accessoryType = lastSelection == indexPath ? .Checkmark : .None

    //other cell configuration

    return cell
}