Alex Stone
Alex Stone

Reputation: 47348

iOS how to get a reference to a view controller embedded in a storyboard container with a segue?

I have a storyboard and a view controller with a container view. Within a storyboard I've defined a connection from the container to another view controller using "Embed" segue. How can I get a reference to the embedded view controller from within a parent view controller?

I've created a reference to the container, but see that it is just a UIView

Here's the segue I'm using enter image description here

enter image description here

Upvotes: 12

Views: 5141

Answers (3)

MischkaTheBear
MischkaTheBear

Reputation: 81

Same answer as above, but in swift:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "nameOfSegueIdentiferFromStoryboard") {
        guard let destinationVC = segue.destination as? ViewControllerClassName else { return }
        destinationVC.someProperty = someValue
    }
}

Upvotes: 2

Wayne
Wayne

Reputation: 3519

Here is an alternative approach using reflection, by implementing:

-(void)addChildViewController:(UIViewController *)childController

e.g.

-(void)addChildViewController:(UIViewController *)childController {

    [super addChildViewController:childController];

    for (UIViewController *childViewController in [self childViewControllers]) {
        if ([childViewController isKindOfClass:[SomeViewController class]]) {
            _controller = (SomeViewController *)childController;            
            break;
        }
    }
}

Upvotes: 0

tdelepine
tdelepine

Reputation: 2016

you must implement the prepareForSegue in main ViewController and specify an identifier in your StoryBoard.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"])
    {
        // Get reference to the destination view controller
        YourViewController *vc = [segue destinationViewController];

    }
}

Upvotes: 17

Related Questions