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
...
}
4

3 回答 3

3

此代码可以帮助您删除子视图,对我来说很好。self.childViewControllers 是一个数组,因此您可以从特定索引中删除。

  [[self.childViewControllers objectAtIndex:0] removeFromParentViewController];
于 2014-03-20T16:25:21.153 回答
2

试试这个

  [self.childviewcontroller willMoveToParentViewController:nil;
  [self.childviewcontroller removeFromParentViewController]; 
  [self.childviewcontroller.view removeFromSuperview];
于 2017-07-12T08:43:24.100 回答
0

我想我想通了:我没有将指针转发给子 VC,而是创建了父 vc 的一个新类,从而导致了新的初始化(恢复所有子 VC)。您应该始终将指向包含类的指针转发给子 VC!

于 2013-02-03T10:39:07.790 回答