Search code examples
iosobjective-cxcodeuiviewcontrolleruistoryboardsegue

Xcode pass data from a viewcontroller to another viewcontroller in a different storyboard


I have two storyboards that contain one view controller each.

storyboard1 --------> viewcontrollerA

storyboard2 --------> viewcontrollerB

How do I pass a string from viewcontrollerA to viewcontrollerB?

Example:

viewcontrollerB.testString=@"The transfer of data worked!";

So far, I know how to transfer views, but I don't know how to transfer data.

This is my code to transfer views:

- (IBAction)moveToViewcontrollerB:(id)sender {

UIStoryboard *storyboard2 = [UIStoryboard storyboardWithName:@"storyboard2" bundle:nil];

UIViewController *viewcontrollerB = [storyboard2 instantiateInitialViewController];

viewcontrollerB.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

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

}

My question is, if I have a string in viewcontrollerB called "testString", how do I update that string in the viewcontrollerA IBaction method?

I only know how to transfer data using segues but since this viewcontroller is on another storyboard, a segue - prepareForSegue won't work.

Thank you in advance.


Solution

  • First of all set Storyboard ID to your SecondView Controller like below image.

    enter image description here

    Then add following code at your button click event.

    - (IBAction)moveToViewcontrollerB:(id)sender {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard2"
                                                             bundle: nil];
        SecondStoryboardVC * secondStoryboardVCOBJ_ = [storyboard instantiateViewControllerWithIdentifier:@"SecondClassStoryboardID"];
        [secondStoryboardVCOBJ_ setStrValue:@"The transfer of data worked!"];
        secondStoryboardVCOBJ_.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:secondStoryboardVCOBJ_ animated:YES completion:nil];
    }
    

    Storyboard2 is storyboard name.

    SecondClassStoryboardID is Storyboard ID which you given in storyboard viewController like above image.

    SecondStoryboardVC is the secondclass name which you want to present