here is my code.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow;
let currentCell = tableView.cellForRow(at: indexPath!) as! monthTableViewCell!;
valueToPass = (currentCell?.monthOutlet.text)!
print(valueToPass)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "toMonthVC") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destination as! monthCellViewController
// your new view controller should have property that will store passed value
viewController.dataFromHoursVC = valueToPass
}
}
So basically I am trying to pass a value from one VC to another. the didSelectRow is working perfectly how expected. However, the prepare function is running late. For example, the first time the code is run, the second vc sees the passed value as nil. But when i go back and then do it again, it says the passed value, but the value is the one that was done before. So simply put it is acting like the prepare function is behind or being called late.
How did you set up your segue? It sounds like the value isn't being set before the segue is performed.
Try doing it this way:
After you give your segue an identification name set up your code like this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow;
let currentCell = tableView.cellForRow(at: indexPath!) as! monthTableViewCell!;
valueToPass = (currentCell?.monthOutlet.text)!
print(valueToPass)
// invoke the segue manually after value is set
self.performSegue(withIdentifier: "SEGUEID", sender: self)
}
Quick Warning
You really should be careful using force unwraps optionalVar!
and force downcasts thing = otherThing as! Type
. It's far better to always use if-let and guard-let statements or fail-able down casts as?
. Using these will decrease the chances of developing a hard to find nil value bug.