Can anyone please help me to pass information about row number selected in tableView? I need it in other view controller to choose data depending on selected row in previous table.
The Xcode blocks returning this data outside function. I cannot manage it for over a week. Thank you in advance.
This is my original code that I have written:
//to object search viewcontroller
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let rowNumber = indexPath.row
print(rowNumber) //just for testing
performSegue(withIdentifier: "ToObjectSearch", sender: self)
}
I have tried this:
//to object search viewcontroller
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) -> Int {
let rowNumber = indexPath.row
print(rowNumber)
performSegue(withIdentifier: "ToObjectSearch", sender: self)
return rowNumber
}
..but it completely blocks segue to next viewcontroller.
The way to pass data through a segue is using prepare(segue:)
Your desttination is a viewController class is DestViewController
Inside, define a property
var rowSelected : Int?In the source controller, declare a var to hold the selection
fileprivate var selectedRow: Int?that you set in didSelectRow
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
rowSelected = indexPath.row
print(rowSelected) //just for testing
performSegue(withIdentifier: "ToObjectSearch", sender: self)
} override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the destination view controller in destVC.
// Pass the selected object to the new view controller.
if let destVC = segue.destination as? DestViewController {
destVC.rowSelected = rowSelected
}
}Note: in the prepare, you should test it is the right segue, so that, if you define other vsegues you know which one to prepare
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the destination view controller in destVC.
// Pass the selected object to the new view controller.
if segue.identifier == "ToObjectSearch"
if let destVC = segue.destination as? DestViewController {
destVC.rowSelected = rowSelected
}
}
}