简体   繁体   中英

Passing data between View Controllers using prepareForSegue

I'm trying to create a simple project to pass some data between two view controllers which I have set up using storyboarding.

The project is very simple - on the first page I have a text field, and then a button takes the user to a second view controller where the text should hopefully be displayed, but as of yet no luck.

I am using the 'Modal' style for the Segue, here is the code:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

ViewController2 *vc2;

vc2 = [segue destinationViewController];

vc2.label.text = textField.text;    

}

I would be grateful if someone could help me out with the correct code and explain to me why what I currently have doesn't work. I've searched around, and while there seem to be several variations as to how this can be done, this seems pretty much correct to me.

I only moved to iOS from the console about two weeks ago, so please keep it simple!

Thanks in advance!

Your problem (probably!) is that the destinationViewController has not yet loaded its view hierarchy at the point where you're trying to update it. You can verify this with:

NSLog(@"Label: %@", vc2.label);

The way around this is to create a property in ViewController2 that is just a string and set that instead. Then, when viewDidLoad: executes in ViewController2 , copy the string property into the label's text.

I know its ugly but try casting the destinationviewcontroller. I've tried it and it seems to help out with situations such as this.

ViewController2 *vc2 = (ViewController * ) [segue destinationviewcontroller];

Also, if you are using storyboards, are you in a uinavigationcontroller or no?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM