How to get the parentViewController in childViewController?

2.9k Views Asked by At

I have a main UIViewController and named AddInformationController. In this mainViewController I have two UIContainerView. Each of them embed with a UITableViewController. The table view controllers are named InformationSegmentController and ResultSegmentController.

I put this in AddInformationController:

InformationSegmentController *isc = [self.storyboard instantiateViewControllerWithIdentfier:@"InformationSegmentController"];
ResultSegmentController *rsc = [self.storyboard instantiateViewControllerWithIdentifier: @"ResultSegmentController"];
[self addChildViewController: isc];
[self addChildViewController: rsc];

In either the InformationSegmentController class or ResultSegmentController class, I tried to Log this: NSLog(@"%@",self.parentViewController); But unfortunately, it is a nil. How can I get the parentViewController correctly? Do I have to use the prepareForSegue?

// Question Update:

I found that I don't have to call addChildViewController method again if I create those childViewControllers directly in my storyboard.

I have tried to NSLog(@"%@", self.childViewControllers) in my AddInformationController and the result contains InformationSegmentController class and ResultSegmentController class.

But the problem is when I call NSLog(@"%@", self.parentViewController) on both childViewContorllers in viewDidLoad, the results is nil.

2

There are 2 best solutions below

4
Vvk On BEST ANSWER

You have to try like this

//add childview
    [self addChildViewController:aVC];
    [self.view addSubview:aVC.view];
    [aVC didMoveToParentViewController:self];

    //remove
    [self removeFromParentViewController];
    [self didMoveToParentViewController:nil];
    [self.view removeFromSuperview];

Hope it Helps you.

OR
another way to get PerentViewController in ChildViewControler is Make @property (strong, nonatomic) AddInformationController *ParentVC; in Your ChildViewController.h and assign viewController from your ParentViewController Like

InformationSegmentController *isc = [self.storyboard instantiateViewControllerWithIdentfier:@"InformationSegmentController"];
isc.ParentVC = self;
[self addChildViewController: isc];
0
iOS Geek On

Give identifiers to both the segues to your container views(suppose "InformationSegmentControllerSegue" and "ResultSegmentControllerSegue" ,namely) and use prepareForSegue in your AddInformationController like this:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
        if ([[segue identifier] isEqualToString:@"InformationSegmentControllerSegue"]) {
            InformationSegmentController *container1 = segue.destinationViewController;
        }
else if([[segue identifier] isEqualToString:@"ResultSegmentControllerSegue"]) {
            ResultSegmentController *container2 = segue.destinationViewController;
        }
    }

Hope this helps you.