Sarah Malik Sarah Malik - 1 month ago 6
Swift Question

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

Answer

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
    }