0

我加載了我的主視圖控制器的視圖。此主視圖控制器然後添加2個子視圖控制器(分割視圖:主和細節)。當我在init方法中添加它們之後立即記錄子VC的數量時,我將'2'作爲輸出。 當我然後調用-switchToCommunication方法並嘗試刪除詳細的子VC時,視圖不會更改。但日誌告訴我,陣列實際上已經從2個孩子VC縮小到1.可可:無法刪除子視圖控制器

這是怎麼回事?

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
[super init]; 

//add master view controller as childVC 
self.test2 = [test2 new]; 
[self addChildViewController:self.test2]; 
self.test2.view.frame = CGRectMake(0, 0, 256, 768); 
[self.view addSubview:self.test2.view]; 
[self.test2 didMoveToParentViewController:self]; 

//add detail view controller as childVC 
self.detail1Vc = [EADetailSupportViewController new]; 
[self addChildViewController: self.detail1Vc]; 
self.detail1Vc.view.frame = CGRectMake(284, 0, 740, 768); 
[self.view addSubview: self.detail1Vc.view]; 
[self.detail1Vc didMoveToParentViewController:self]; 
NSLog(@"Child VC in childVC array: %d", [self.childViewControllers count]); 



- (void) switchToCommunication { 
//remove currently active detail view controller from parent view 
NSLog(@"Child VC in childVC array: %d", [self.childViewControllers count]); 


[[self.childViewControllers lastObject] willMoveToParentViewController:nil]; 
[[[self.childViewControllers lastObject] view] removeFromSuperview]; 
[[self.childViewControllers lastObject] removeFromParentViewController]; 

NSLog(@"Child VC in childVC array: %d", [self.childViewControllers count]); 

NSLog(@"pushed"); 

//add communication detail view controller as child view controller 
... 
} 
+0

我想你的代碼,它爲我工作得很好。 – rdelmar

+0

在加載視圖之前調用viewDidLoad並且在你的init中甚至是BAD/WRONG :)改變那個+ init應該總是調用[super init] –

+0

不用擔心 - 我調用[super init] - 複製粘貼錯誤來啓動init方法! –

回答

0

我想我想通了:不是轉發的指針孩子的VC,我只是創造了一個新的類產生了新initalization父的VC(reinstatiating所有子VCS)。你應該總是將一個指向包含類的指針傳給子VC!

2

此代碼可能會幫助您刪除子視圖,爲我工作很好.self.childViewControllers是一個數組,因此您可以從特定索引中刪除。

[[self.childViewControllers objectAtIndex:0] removeFromParentViewController]; 
2

嘗試這個

[self.childviewcontroller willMoveToParentViewController:nil; 
    [self.childviewcontroller removeFromParentViewController]; 
    [self.childviewcontroller.view removeFromSuperview];