actuarial
actuarial

Reputation: 73

How to ensure didSelectRowAtIndexPath opens correct View

I know how to send the user to a new cell after they select a cell but what if the order of my cells change because I am retrieving data from Parse so for each new cell, the row number changes.

How do I ensure the user is sent to the correct page when they select a certain cell? This is what I'm currently using but I know there's got to be a better solution than hardcoding every possible option..

Any advice?

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.section == 0 && indexPath.row == 1 {
        self.performSegueWithIdentifier("toSettingsPage", sender: self)
    }
}

Upvotes: 2

Views: 62

Answers (2)

tacos_tacos_tacos
tacos_tacos_tacos

Reputation: 10585

Your input:

  • A table view
  • An index path (section, row) ordered pair

Your output:

  • A string that identifies a segue

An ideal data structure for this is a dictionary.

First, notice that the table view input is always the same (you only seem to care about one table view - the protocol for data source is written to handle as many table views as you like, but most people use one for one).

Second, think about your keys and values: your key is the index path. And in fact, the index path breaks down into just an Integer because it is always the same section, which is analogous to the situation with table view described above.

So your dictionary is going to be of type: Dictionary<Integer, String>.

Now, instead of using the dictionary directly, let's make a function to wrap it and call the function segueForIndexPathInDefaultTableView:

private let seguesForIndexPaths:[Integer:String] = [0:"segue0",1:"segue1",2:"segue2"]

private func segueForIndexPathInDefaultTableView(indexPath: NSIndexPath) {
    return self.seguesForIndexPaths[indexPath.row]
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {      
    self.performSegueWithIdentifier(self.segueForIndexPathInDefaultTableView(indexPath: indexPath), sender:self)
}

Upvotes: 0

Vigor
Vigor

Reputation: 1754

For my understanding of your questions, I suggest you use a NSMutableDictionary to store all the user info data, and on the didSelectRowAtIndexPath function, you will use the indexPath to find the correct user info.

Upvotes: 1

Related Questions