Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Data between View Controllers in Swift

I am trying to convert an app from Objective-C to Swift but I can't find how to pass data between views using Swift. My Objective-C code is

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; AnsViewController *ansViewController; ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"]; ansViewController.num = theNum; [self presentViewController:ansViewController animated:YES completion:nil]; 

What that is doing is it basically takes the variable, theNum, and passes it to the variable, num, on a different view controller. I know this may be an easy question but I am getting pretty confused with Swift so if someone could explain how they changed it to Swift that would be greatly appreciated!

Thanks

like image 793
lagoon Avatar asked Jun 14 '14 17:06

lagoon


1 Answers

Let's assumed we stand at the firstView go to the DetailView and want passing data from firstView to Detailview. To do that with storyboard, at the firstView we will have a method:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {     if (segue.identifier == "segueTest") {       //Checking identifier is crucial as there might be multiple       // segues attached to same view       var detailVC = segue!.destinationViewController as DetailViewController;       detailVC.toPass = textField.text     } } 

and then into the class of DetailView we declared a variable:

var toPass: String! 

then you can use the variable toPass (of course you can change the type of the variable as you want, in this EX I just demo for string type).

like image 126
lee Avatar answered Sep 23 '22 00:09

lee