Search code examples
swiftuitableviewobjectsegue

Passing Object from Table View Cell to Another View Controller Via Segue


I have the following portion of my code that I'm trying to work out in order to move from a table view controller to a view controller.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
   let donation = donations[indexPath.row]
   print(donation)
   self.performSegue(withIdentifier: "showDonationReviewForm", sender: Any?)
}

On the above, when I print donation, it correctly prints the object and it's related fields. I know at some point I would need to use override func prepare(for segue... but I don't know how I am passing along the donation object to the next controller.


Solution

  • You can try

    performSegue(withIdentifier: "showDonationReviewForm", sender:donations[indexPath.row])
    

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDonationReviewForm" {
            if let nextViewController = segue.destination as? NextViewController {
                nextViewController.toSend =  sender as! Donation 
            }
        }
    }
    

    class NextViewController :UIViewController {
       var toSend:Donation?
       ....
    }
    

    Assuming donations is an array of Donation model