2013-07-27 23 views
0

我的ViewController有孩子,它的偉大工程,但是當我改變根視圖到另一個,然後返回背根視圖:的setView與ChildViewController

-(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>' 

使用子視圖控制器更改根視圖的正確方法是什麼?

回答

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

這樣你就可以改變你的根視圖。

+0

我該如何刪除視圖控制器,其實是哪裏?我可以改變視圖,當viewcontroller沒有孩子只是使用setView屬性。 – HotJard

相關問題