Daisy R.
Daisy R.

Reputation: 633

Save Selected Row in UITableView To NSUserDefaults

I'm trying to save the selected state of a row so that when the tableview loads the selected row's corresponding checkmark appears. I've tried this method below in viewDidAppear but it's not working.

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")

Upvotes: 1

Views: 1008

Answers (2)

ZHZ
ZHZ

Reputation: 2098

Move this to viewDidLoad()

lastSelection = NSIndexPath(forRow: checkMarkToDisplay, inSection: 0)

and delete this

self.tableView.cellForRowAtIndexPath(lastSelection)?.accessoryType = .Checkmark

Then add this to

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

    //other cell configuration

    return cell
}

Upvotes: 0

Dharmbir Singh
Dharmbir Singh

Reputation: 17535

Please implement your logic in cellForRowAtIndexPath and remove your checkmark code from viewDidAppear.

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
    }
}

Upvotes: 1

Related Questions