0

我有带孩子的 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>'

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

4

2 回答 2

2

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

NSMutablearray *controllers = [self.navigationController viewcontrollers];

[控制器 removeObjectAtIndex:0];

它将删除 rootviewController 和命名方式,您可以添加新的视图控制器。

[控制器 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;

这样你就可以改变你的根视图。

于 2013-07-27T14:04:31.093 回答
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];
    }
} 
于 2013-07-27T15:00:43.890 回答