可可:无法删除子视图控制器



我加载了主视图控制器的视图。然后,此主视图控制器添加 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
...
}

这段代码可以帮助你删除子视图,对我来说工作正常.self.childViewController是一个数组,所以你可以从perticular index中删除。

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

试试这个

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

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

最新更新