1

Here is the code I currently have:

var valueToPass:String!

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    valueToPass = currentCell.textLabel.text // valueToPass now equals "test"
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var viewController = segue.destinationViewController as AnotherViewController
    viewController.passedValue = valueToPass // valueToPass equals nil here? Why?
}

as you can see, i have assigned "test" to valueToPass in didSelectRowAtIndexPath but in prepareForSegue, valueToPass is nil? why?

johnniexo88
  • 313
  • 5
  • 17
  • is your tableview laid out in a storyboard with the segue? if that's the case I'm not certain `tableView:didSelectRowAtIndexPath:` actually gets called before `prepareForSegue:sender:`. You could test this by dropping breakpoints in both methods and seeing which on trips first when tapping on the cell. Try to keep `prepareForSegue:sender:` free of implicit dependencies on other methods – markedwardmurray Jul 23 '16 at 17:51

1 Answers1

1

Try replacing:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let indexPath = tableView.indexPathForSelectedRow();
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell!;

    valueToPass = currentCell.textLabel.text // valueToPass now equals "test"
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

With this:

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

    let currentCell = tableView.cellForRowAtIndexPath(indexPath.row) as! UITableViewCell;

    valueToPass = currentCell.textLabel.text! // valueToPass now equals "test"
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)

}

Also, when you made the segue in the storyboard, make sure you DID NOT drag from the tableview to the next viewcontroller. This is because if you do this automatically, then perform segue will be called BEFORE didSelectRow... making it perform the segue before you set the value. Just drag from the viewcontroller that hosts the table view to the new view.

Tob
  • 985
  • 1
  • 10
  • 26
  • "Also, when you made the segue in the storyboard, make sure you DID NOT drag from the tableview to the next viewcontroller. This is because if you do this automatically, then perform segue will be called BEFORE didSelectRow... making it perform the segue before you set the value. Just drag from the viewcontroller that hosts the table view to the new view. " That was the problem. thanks so much! – johnniexo88 Jul 23 '16 at 18:12