Alson Chi Alson Chi - 6 months ago 21
JSON Question

How to get indexPath match I click send data with segue

I hope when i click the UITableView row
it will send a ID to next UIView
the ID get form json data
I can not get the UITableView indexPath
have some error.
How can I fix this ?

this is my code

func get(){
let url = NSURL(string: "http://test.php?id=01")
let data = NSData(contentsOfURL: url!)
values = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
tableView1.reloadData()
}

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! SpecialCell
let maindata = values[indexPath.row]
cell.name.text = maindata["product"] as? String
cell.vintage.text = maindata["vintage"] as? String

ID = maindata["ID"] as? String


return cell;
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){
if segue.identifier == "showWineDetail"{
if indexPath = self.tableView1.indexPathForSelectedRow{
let destination = segue.destinationViewController as! ViewController
destination = self.ID
}
}
}


}

Answer
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["product"] as? String
    cell.vintage.text = maindata["vintage"] as? String

    return cell;
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){
    if segue.identifier == "showWineDetail"{
        if let indexPath = self.tableView1.indexPathForSelectedRow{
            let destination = segue.destinationViewController as! ViewController
            let maindata = values[indexPath.row]
            destination.ID = maindata["ID"] as? String
        }
    }
}

Create in destination(ViewController) var ID:String = ""