如何在childViewController中获取parentViewController?

时间:2016-03-31 03:46:06

标签: ios objective-c childviewcontroller parentviewcontroller

我有一个主UIViewController并命名为AddInformationController。在此mainViewController中,我有两个UIContainerView。他们每个人都嵌入UITableViewController。表视图控制器名为InformationSegmentControllerResultSegmentController

我把它放在AddInformationController

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

InformationSegmentController类或ResultSegmentController类中,我尝试记录此: NSLog(@"%@",self.parentViewController); 但不幸的是,这是一个零。如何正确获取parentViewController?我必须使用prepareForSegue吗?

//问题更新:

如果我直接在故事板中创建了这些childViewControllers,我发现我不必再次调用addChildViewController方法。

我在NSLog(@"%@", self.childViewControllers)尝试了AddInformationController,结果包含InformationSegmentController类和ResultSegmentController类。

但问题是当我在NSLog(@"%@", self.parentViewController)的两个childViewContorllers上调用viewDidLoad时,结果为零。

2 个答案:

答案 0 :(得分:1)

你必须尝试这样

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

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

希望它能帮到你。


另一种在PerentViewController中获取ChildViewControler的方法是在@property (strong, nonatomic) AddInformationController *ParentVC;中设置ChildViewController.h,并从viewController

分配ParentViewController
InformationSegmentController *isc = [self.storyboard instantiateViewControllerWithIdentfier:@"InformationSegmentController"];
isc.ParentVC = self;
[self addChildViewController: isc];

答案 1 :(得分:0)

为容器视图的segue提供标识符(假设" InformationSegmentControllerSegue"" ResultSegmentControllerSegue&#34 ;,即)并在AddInformationController中使用prepareForSegue,如下所示:

    - (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;
        }
    }

希望这会对你有所帮助。