Sashi
Sashi

Reputation: 533

IOS/Swift: Save the cell selection on UITableView

I have a master detail layout with table views in both of the views. Left panel has a list of patients and right has a list of documents, what happens is by changing the patient selection documents will be reloaded and if the user clicks on a document, it will segue to a webView to display PDF.

For consistency purpose i made the first cell in the Patient table to be selected by default using the below code

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)
    let rowToSelect:NSIndexPath = NSIndexPath(forRow: 0, inSection: 0);
    self.tableView.selectRowAtIndexPath(rowToSelect, animated: true, scrollPosition: UITableViewScrollPosition.None)
    self.performSegueWithIdentifier("showDetail", sender: self)
  }

work's fine right?, Yes but it gets a bit inconsistent from here, after closing this PDF document (by clicking done on navigation), my Previously selected cell will go off and it again points to the first Patient. Is there any way to save this selection? Oh and even to save the selection on the details page too. Thanks.

Upvotes: 0

Views: 2090

Answers (1)

Lord Zsolt
Lord Zsolt

Reputation: 6557

Create an NSIndexPath property.

Change your viewDidAppear to only default-select the first cell if there wasn't something previously selected:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)
    if (!self.rowToSelect) {
        rowToSelect = NSIndexPath(forRow: 0, inSection: 0);
        self.tableView.selectRowAtIndexPath(rowToSelect, animated: true, scrollPosition: UITableViewScrollPosition.None)
        self.performSegueWithIdentifier("showDetail", sender: self)
    }    
  }

In the didSelectRow delegate method store the selected index path in self.rowToSelect.

Upvotes: 4

Related Questions