问题
I have a tableviewcontroller named DetailTableViewController and I need to pass data to next tableviewcontroller named DetailTableViewController. But I need to pass the data as the user clicks the cell of DetailTableViewController. Then, I got error as "unexpectedly found nil while unwrapping an Optional value".Please help me sort out in Swift 3.
回答1:
First create a variable in your detail view controller to hold the value which you send from first view controller. then assign the value inside the didSelectRowAt method in first view controller and then navigate programatically. in this way, you do not need to implement prepare for segue method to send the data.
you just need to implement the didselectrowat, method.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selected = firstArray[indexPath.row]
let detailvc = self.storyboard?.instantiateViewController(withIdentifier: "DetailTableViewController") as! DetailTableViewController
detailvc.type = selected
self.present(detailvc, animated: true, completion: nil)
}
I created a video tutorial for you from scratch. how to pass data from one table view controller to another. hope this will help to you.
回答2:
First of all, never get data from the view (the cell) in such a case, get it always from the model (data source array).
Second of all, the signature of
prepare(for segueis wrong for Swift 3.
In didSelectRowAt pass the indexPath rather than self, you can also delete valueToPass.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "Cell", sender: indexPath)
}
In prepareForSegue get the data from the model and pass it to the detail view controller:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Cell" {
let viewController = segue.destination as! GuidesDetailsTableViewController
let indexPath = sender as! IndexPath
viewController.passedValue = guides[indexPath.row]
}
}
回答3:
Inside your didSelectRow you're setting a new indexPath. Removing it should do the trick.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Don't reassign indexPath
// let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
valueToPass = currentCell.textLabel?.text
performSegue(withIdentifier: "Cell", sender: self)
}
回答4:
It seems that the var valueToPass don't have a value when you call the performSegue. Try to assign the value of valueToPass with the following code:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
valueToPass = guides[indexPath.row]
performSegue(withIdentifier: "Cell", sender: self)
}
And create your segue form your viewController, maybe you create the segue from the cell.
来源:https://stackoverflow.com/questions/42739412/send-data-from-tableviewcontroller-to-detailviewcontroller