Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variables between view controller using presentViewController in iOS SDK?

some days ago I wrote a method to load a view controller using presentViewController:

-(void)passaGC:(NSString *)user
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *viewController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"generaC"];
[self presentViewController:viewController animated:YES completion:nil];

}

But today I need to pass the variable user from this method to the loaded viewController.

How can I modify my method to do this?

I found other question on stack overflow but nothing is really similar to my request

like image 862
Gualty Avatar asked Mar 09 '14 13:03

Gualty


2 Answers

add a property to your destination viewController (in the .h):

@property (strong, nonatomic) NSString *user;

and finally your method will look like

-(void)passaGC:(NSString *)user
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *viewController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"generaC"];

viewController.user = user;

[self presentViewController:viewController animated:YES completion:nil];

}
like image 198
Armand DOHM Avatar answered Nov 13 '22 13:11

Armand DOHM


Swift Solution

Except @IBOutlets, you can simply assing data to destination view controller properties.

DestinationVC.swift

var name: String?

SourceVC.swift

let storyboard = UIStoryboard(name: "Helper", bundle: nil)
let destinationVC = storyboard.instantiateViewControllerWithIdentifier("DestinationSID") as! DestinationVC
destinationVC.name = "Mustafa"
presentViewController(destinationVC, animated: true, completion: nil)
like image 4
muhasturk Avatar answered Nov 13 '22 14:11

muhasturk