Search code examples
iosswiftuistoryboardseguedidselectrowatindexpath

Segue in cellForRowAtIndexPath doesn't send data


In my didSelectRowAtIndexPath I try to set some data and finally do a segue.

Code looks like this:

    func tableView(tableView: UITableView, DidSelectRowAtIndexPath indexPath: NSIndexPath) {

    var cell = tableView.cellForRowAtIndexPath(indexPath)


    otherName = groupIds[indexPath.row] as! String

    otherActualName = groupNames[indexPath.row] as! String

    self.performSegueWithIdentifier("matchToConversation", sender: self)
}

otherName and otherActualName are declared as global variables.

If I put breakpoints the global variables are getting their right values. If I don't it doesn't work. I think my Segue is triggered before the data is assigned since they are products of a PFQuery.

I tried to use the prepareForSegue function, but I'm not sure how to use it here. Any Advice?


Solution

  • prepareForSegue will let you assign those variables to your next view controller. Let's say you're pushing a viewController and you want to pass those 2 params, you could use prepare for segue this way.

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)     
    {
      if segue.identifier == "YOUR_SEGUE_IDENTIFIER" {
        let destinationController = segue.destinationViewController as! YourNextViewController
        destinationController.otherName = self.otherName
        destinationController.otherActualName = self.otherActualName
      }
    }
    

    If your groupIds and groupNames arrays are populated when tableView(_:didSelectRowAtIndexPath:) is called, the values should be passed no problem.

    What you need is define your new view controller like so

    class YourNextViewController: UIViewController
    {
      var otherName: String? 
      var otherActualName: String?
    }
    

    That way you can pass your values in prepareForSegue