Pedro Francisco
Pedro Francisco

Reputation: 29

passing data between viewControllers late

1) Basically, data is passing through ViewControllers, but is getting late. When nextViewController is executing code, some variables passed on

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "goto") ...

aren't set yet. Are still nil.

2) My second issue is related with first one: I am trying to pass data from selectedCell, so I am assigning a global variable on the delegate didSelectItemAtIndexPath. but when it reaches prepareForSegue, that variable I am going to pass is still nil.

Any help, please?

Upvotes: 0

Views: 89

Answers (1)

Jen Jose
Jen Jose

Reputation: 4045

You should either use the segue OR the table view delegate.

  1. Setting Segue from TableviewCell to DetailViewController in Storyboard :-

Get the selected tableview cell in PrepareForSegue and access the appropriate data and pass onto next DetailVC.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    //get the selected indexPath
    let selectedIndex = self.tableView.indexPathForCell(sender as UITableViewCell)
    var dataTobePassed = dataArray[selectedIndex.row]
        destination.data = dataTobePassed
}

-OR-

  1. If there is segue between the two ViewControllers, then on tableview selection delegate method, you set the segue.

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.performSegueWithIdentifier("showDetailVC", sender: indexPath); }

Then in your prepareForSegue method

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "showDetailVC") {

        let path = self.tableView.indexPathForSelectedRow()!
        segue.destinationViewController.detail = self.detailForIndexPath(path)
      }
    }

Upvotes: 1

Related Questions