使用ChildViewController的setView

时间:2013-07-27 12:22:48

标签: ios ipad

我有带子的ViewController,它的效果很好,但是当我将根视图更改为另一个时,然后返回根视图:

-(void)showSearchResultView
{
    self.searchView.frame = self.view.frame;
    __rootView = self.view;
    [self setView:self.searchView];
}

-(void)hideSearchResultView
{
    if(__rootView) [self setView:__rootView];
    __rootView = nil;
}

我得到了例外:

Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', 
reason: 'child view controller:<SlideViewController> should have parent view controller:
<UINavigationController> but actual parent is:<MainViewController>'

使用子视图控制器更改根视图的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

要更改根视图,您必须从导航堆栈中删除rootviewcontroller。 喜欢:

NSMutablerray * controllers = [self.navigationController viewcontrollers];

[controllers removeObjectAtIndex:0];

它将删除rootviewController和名称,以便添加新的视图控制器。

[controllers addObjectAtIndex:0];

注意: - 此代码语法可能不正确。这只是一种方法。

更新: -

NSMutableArray *viewControllers = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];

RootViewController *root = [[RootViewController alloc]initWithNibName:@"RootViewController" bundle:nil];

[viewControllers insertObject:root atIndex:0];
self.navigationController.viewControllers = viewControllers;

这样您就可以更改根视图。

答案 1 :(得分:0)

我找到了解决方案。只需删除子根视图并重新添加即可。

-(void)showSearchResultView
{
    self.searchView.frame = self.view.frame;
    __rootView = self.view;
    [self setView:self.searchView];

    for(UIViewController* vc in self.childViewControllers){
        [vc.view removeFromSuperview];
    }
}

-(void)hideSearchResultView
{
    if(__rootView) [self setView:__rootView];
    __rootView = nil;

    for(UIViewController* vc in self.childViewControllers){
        vc.view.frame = self.view.bounds;
        [self.view addSubview:vc.view];
    }
}