Kunal Parekh
Kunal Parekh

Reputation: 370

ios Swift: Passing data from tableView to view controller

enter image description herewell this is my first time posting a question so not to sure how it works. I am doing an assignment on swift. I am stuck at a point where I need to pass the data from tableview to viewcontroller. On my first ViewController, I have a list of data (Categories) coming from the database table and when the user clicks on any of the cell, it should go to the next viewcontroller the label becomes the heading. Please find my screen shot attached.

Thanks

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return values.count;
}    

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CategoryList_TableViewCell
    let maindata = values[indexPath.row]
    cell.categoryLabel.text = maindata["NAME"] as? String
    return cell;

}

I tried using didSelectRowAtIndexpath and perparesegue functions but not getting my head around.

can anyone can guide me.

Thanks a million in advance :)

screenshot of the table

Upvotes: 2

Views: 5382

Answers (2)

nighttalker
nighttalker

Reputation: 946

You don't need to implement didSelectRow just to pass data through a segue. Assuming you're using Storyboards.

  1. CTRL drag from the prototype TableViewCell in your storyboard to the ViewController you want to pass data to.

  2. Choose Show for the segue type and give it an identifier

  3. Do this in prepareForSegue:

    if segue.identifier == "catView" {
        if let indexPath = self.tableView.indexPathForSelectedRow {
            let controller = segue.destinationViewController as! YourViewController
            let value = values[indexPath.row]
            controller.catTitleRec = value["NAME"] as! String
    }
    

Upvotes: 5

gasparuff
gasparuff

Reputation: 2295

Do this in your didSelectRowAtIndexPath:

let maindata = values[indexPath.row]
self.performSegueWithIdentifier("yourIdentifier", sender: mainData)

Then, in your prepareForSegue function do this:

let destinationVC = segue.destinationViewcontroller as! YourCustomViewController
destinationVC.yourObject = sender as! YourObject

Upvotes: 1

Related Questions