Search code examples
iosiphonexcodeswiftios9

How do I pass information from a table view cell in one view controller to another view controller?


So, I have 2 View Controllers:

  1. A Table View Controller with a list of club names that can be pressed. It has a custom class called ClubsTableViewController.
  2. A View Controller that I will use to display a description of the club that is pressed. I want to reuse this view controller to display different information based on whichever club is pressed. It has a custom class called ClubDetailViewController.

Two view controllers I have created segues between each Table View Cell of the Table View Controller and the second View Controller and each segue has the identifier "showClubDetails".

I have the following method in the ClubsTableViewController.swift file:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showClubDetails" {
        let detailsController = segue.destinationViewController as! ClubDetailViewController;
        if let name = self.view.viewWithTag(1) as? UILabel {
            detailsController.clubNameString = name.text!
            detailsController.clubDescriptionString = clubDescriptions[name.text!]!
        }
    }
}

I use this method to pass the name of the club that was pressed from the 1st view controller to the second one. The code above works for the 1st cell of the Table View ("Amnesty International" in the image above) because I have given it the tag 1.

However, I want to pass the name of any club that is pressed to the second view controller and I am not quite sure how to do this. Any help would be appreciated. Thanks!


Solution

  • Your segue should look like this:

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "showClubDetails" {
    
        let indexPath:NSIndexPath = tableView.indexPathForSelectedRow!
    
        let detailsController = segue.destinationViewController as! ClubDetailViewController;
    
            detailsController.clubNameString = names[indexPath.row]
            detailsController.clubDescriptionString = clubDescriptions[indexPath.row]
    }
    

    }

    EDIT:

    indexPath takes index of your clubs and then correctly send name of club from an array. That means clubs names must be in an array (same as the clubs description).