简体   繁体   中英

ios Swift: Passing data from tableView to view controller

enter image description here well 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 :)

表格截图

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 } 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM