Runeaway3
Runeaway3

Reputation: 1447

How to make prepare for segue specific to one particular segue?

I have a some code set up with a prepare(for segue:) being used to pass information from the current tableviewcontroller to the destination one. This prepare for is intended to be used for when any of the cells in the table are selected, however, this is not the only segue from that viewcontroller. There are other segues that come from buttons clicked, but I think the way that I have the information pass set up is generic for any segue... meaning when the button segues are clicked, the way the code is set up the app is expecting to see the the VC from the cell's segue. Since it doesn't the app crashes. How do I set my code so that the prepare for function is not general to any story board segue (as I think it currently is) but instead to specifically the cell segue? Here is the current set up:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let indexPath = self.tableView.indexPathForSelectedRow
        let rowSelectedd = indexPath
        let destViewController: MainPageCellSelectedViewController = segue.destination as! MainPageCellSelectedViewController
        destViewController.rowSelected = rowSelectedd!
    }
    var rowSelectedd = IndexPath()
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "cellSelected", sender: rowSelectedd)
    }

I believe the problem is (correct me if I'm wrong) in the for segue: UIStoryboardSegue not being specific, but I don't know how to set up an identifier there.

Upvotes: 2

Views: 1324

Answers (2)

Josh Homann
Josh Homann

Reputation: 16327

You can use the identifier, but I hate using string identifiers and its not very swifty. I find I almost always disambiguate the segue by checking the type of the destination viewcontroller with as? and the type of the sender with is or (as in the case of multiply UIButtons) operator ===.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? DetailViewController {
       if sender is UITableViewCell {
          destination.mode = .view
       } else if sender === plusButton {
          destination.mode = .add
       } else if sender === editButton {
          destination.mode = .edit
       }
    }
}

Upvotes: 1

matt
matt

Reputation: 535138

If you configured this correctly, the segue has an identifier for this very purpose. Check the identifier and bow out if it's the wrong one:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard segue.identifier == "cellSelected" else {return}
    // ...
}

Upvotes: 4

Related Questions