Tom F
Tom F

Reputation: 361

How to segue from one tableview to another in Xcode using swift

I'm hoping someone could give me a hand on a way to segue from one tableview to another. I have one tableview pulling information from parse.com and loading up the tableview cells. I would like to have it so when I click on one of those cells it brings me to another tableview thats pulling information from parse.com.

Upvotes: 0

Views: 651

Answers (1)

Mattias
Mattias

Reputation: 415

The data you want to show in the second UITableViewController probably depends on which cell you tapped in the first one, right? Then you need to pass the data from your first UITableViewController to your second.

If you're using storyboards I'd suggest (I think this is the easiest way, but I don't know if it's the best) you create a segue from the first UITableViewController to the other, and naming it properly. Then use prepareForSegueto feed that data into the next Table. If you're just using a single Parse query you can simply copy the result array from your query to your class.

//In your class declaration
var objects = [PFObject]()

//In your query method
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
    if let results = objects as! [PFObject] {
    self.objects = results }
}    

Perform segue in didSelectRowAtIndexPath

performSegueWithIdentifier("mySegue", sender: self)

And implement prepareForSegue to fit your needs.

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    //Check that the segue is the right one
    if segue.identifier == "mySegue" {

        if let destination = segue.destinationViewController as? MySecondTableViewController {
            //Grab the data from your array
            if let indexPath = tableView.indexPathForSelectedRow()?.row {
                if let objectToPass = objects[indexPath] as? PFObject {
                //Assuming your destination VC has a variable named object, type PFObject?
                destination.object = objectToPass
                }
            }
        }
    }
}

Then, in your next UITableViewControlleryou can use object to perform a new query for the second table. Example:

//Second UITableViewController
//If you're using PFTableQueryViewController, use the queryForTable method 
let query = PFQuery(classname: "Animals")
query.whereKey("owner", equalTo: object) //Object comes from your first table
query.findObjectsInBackgroundWithBlock{
(...) }

Edit: This is almost exactly what they're doing in the link Steve posted, but I've made some examples hopefully fitting to your case.

Upvotes: 1

Related Questions