bhavya kothari
bhavya kothari

Reputation: 7474

Passing data between two UIViewControllers using Swift and Storyboard

I was using below code to selected UITableView to pass data between UIViewControllers

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        RecipeDetailViewController *destViewController = segue.destinationViewController;
        destViewController.recipeName = [recipes objectAtIndex:indexPath.row];
    }
}

How to do same thing using swift with tableView selected data?

I have tried below approach for simple passing which is working
but How to replicate above mentioned case.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    var detailsVC = segue.destinationViewController as SecondViewController

    detailsVC.passedString = "hello"

}

Upvotes: 2

Views: 1320

Answers (2)

Greg
Greg

Reputation: 25459

This should work:

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

            var detailsVC = segue.destinationViewController as SecondViewController
            let indexPath = tableView.indexPathForSelectedRow()
            detailsVC.passedString = recipes![indexPath?row]
            //or try that if above doesn't work: detailsVC.passedString = recipes[indexPath?row]
        }
    }
}

This line could require amendments:

destViewController?.destViewController.recipeName = recipes![i]

it depends is you properties optional or not (maybe you have to remove ? or !)

Upvotes: 4

Suresh Kumar Durairaj
Suresh Kumar Durairaj

Reputation: 2126

Try this... If you're first view controller is embedded inside Navigation Controller, you can push the second view controller on didSelectRowAtINdexPath delegate, as below...

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // Create a storyboard instance.....
    var storyBoard = UIStoryboard(name: "Main", bundle: nil)
    // Create a SecondViewController instance, from the storyboardID of the same.
    var seconVC = storyBoard.instantiateViewControllerWithIdentifier("seconViewControllerID") as SecondViewController
    seconVC.passedString = receipes[indexPath.row] as String
    self.navigationController?.pushViewController(secondVC, animated: true)
}

Upvotes: 0

Related Questions