如何在用户默认值中保存indexPath以及如何在加载时预先选择了tableview中的单元格? (xcode 8,swift 3.0)

时间:2017-04-02 01:25:19

标签: ios swift uitableview nsuserdefaults

所以我一直在互联网上寻找答案,但无济于事。基本上,我有代码让tableview中的单元格在选中时有一个复选标记,这很好。但是,选中后,我希望indexPath保存在用户默认值中,以便下次用户查看时,可以预先选择之前选择的特定单元格:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.accessoryType = .checkmark
        UserDefaults.standard.set(indexPath as IndexPath, forKey: "OnHomeShow")
    }

}

override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) {
        cell.accessoryType = .none
    }

}

用户默认保存不起作用!有人能帮忙吗?此外,我如何获得它以便我可以预先选择单元格?我在这里使用了这段代码:

    override func viewDidAppear(_ animated: Bool) {
    if let x = UserDefaults.standard.object(forKey: "OnHomeShow") as? IndexPath
    {
        //I want to pre-select the cell set by the user-default
    }
    else
    {
        //I want to pre-select the first cell
    }
}

但是我不知道用什么代码来编程选择一个单元格!有谁知道如何帮忙?谢谢!

0 个答案:

没有答案