Search code examples
swiftuistoryboardsegue

Swift Prepare(for: segue) not called


In my storyboard controller1 has natigationController and segues to controller 2. It is weird that the Segue works ok but

override func prepare(for: segue)

the whole method was not called (I set breakpoint). I reviewed a lot of old questions on stackoverflow, but no one could solve my problem. Thanks!

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    self.navigationController?.performSegue(withIdentifier: segueId, sender: nil)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == self.segueId {
        let destionationNVC = segue.destination as! UINavigationController
        guard let targetVC = destionationNVC.topViewController as? ViewController2 else { return }

        targetVC.text = self.text
    }
}

Solution

  • You are calling performSegue on self.navigationController, so it's the navigationController.prepareForSegue that will be called, not the one in your VC. You should reconnect the segue to your VC in the storyboard, give it the identifier, and call:

    self.performSegue(...)