简体   繁体   中英

Passing label data from a tableview to another view controller

I'm using this video as example to what I did with my code below. Swift To MYSQL using PHP I used the second half of the video when getting the data from the PHP into the tableview. I was able to get the tableview to display the items from the php successfully in the table view cell rows.

import Foundation
import UIKit
import WebKit

class BreakfastGetController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var tableView: UITableView!


var values:NSArray = []

override func viewDidLoad() {
    super.viewDidLoad()
    get();

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func get(){
    let url = NSURL(string: "http://cgi.soic.indiana.edu/~team20/BreakfastGetInfo.php")
    let data = NSData(contentsOfURL: url!)
    values = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
    tableView.reloadData()
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return values.count;
}
//call the specific row and displying in the cell row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! SpecialCell
    let maindata = values[indexPath.row]
    cell.name.text = maindata["name"] as? String
    return cell;

}

}

Each cell row has a label and that label displays the data I am pulling from the php. My question is, can I push (or show) that data from the label to another view controller with a button? Kind of like a shopping cart, I want to use a button in the row that adds the label to another view controller, so I can view it there (as another label or some other method).

I know there may be similar posts about passing data to another view controller, but there were none that I think I could use (or at least found) that is similar to this.

Yes. Possible.

You want to pass the data from the Tableview to Next View Controller. Right?

Write the Tableview Delegate Method

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    var value = contentArray.objectAtIndex(indexPath.row)

    var secondVC : SecondViewController
        = self.storyboard ?.instantiateViewControllerWithIdentifier(identifier: "SecondViewController")

    secondVC.contentValue = value as? String

    self.navigationController ?.pushViewController(secondVC, animated: YES)

}

Hope it helps.

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