在UIContainerView中对2个UIViewControllers进行动画处理

时间:2018-09-25 13:12:03

标签: objective-c xcode uiviewcontroller uicontainerview ios12

大家好,我正在为UIContainerView内部的2个UIViewController的动画制作动画。为了展示视图控制器,我实现了此方法

#pragma mark - Animation Controller
-(void)moveViewControllerFrom:(UIViewController *)currentViewController toViewController:(UIViewController *)nextViewController {

    CGFloat widthVC = self.containerView.frame.size.width;
    CGFloat heightVC = self.containerView.frame.size.height;

    if (currentViewController == nextViewController) return;

    if (_isNextViewController) {
        nextViewController.view.frame = CGRectMake(widthVC, 0, widthVC, heightVC);
        [self addChildViewController:nextViewController];
        [currentViewController willMoveToParentViewController:nil];

        [self transitionFromViewController:currentViewController toViewController:nextViewController duration:.4 options:0 animations:^{

            nextViewController.view.frame = currentViewController.view.frame;
            currentViewController.view.frame = CGRectMake(0 - widthVC, 0, widthVC, heightVC);
        }
                                completion:^(BOOL finished) {
                                    [currentViewController removeFromParentViewController];
                                    [nextViewController didMoveToParentViewController:self];
                                }];
    }

    else {
        nextViewController.view.frame = CGRectMake(0 -widthVC, 0, widthVC, heightVC);
        [self addChildViewController:nextViewController];
        [currentViewController willMoveToParentViewController:nil];

        [self transitionFromViewController:currentViewController toViewController:nextViewController duration:.4 options:0 animations:^{

            nextViewController.view.frame = currentViewController.view.frame;
            currentViewController.view.frame = CGRectMake(widthVC, 0, widthVC, heightVC);
        }
                                completion:^(BOOL finished) {
                                    [currentViewController removeFromParentViewController];
                                    [currentViewController didMoveToParentViewController:self];
                                }];
    }
}

现在,当我快速按下前进和后退按钮(我用来显示新视图控制器或返回到先前视图控制器的按钮)时,我遇到了问题。我的应用程序crasha和consol将此错误返回给我:

  

***由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'子级视图控制器    和    必须有一个共同的父母   调用-[UIViewController时的视图控制器   transitionFromViewController:toViewController:duration:options:animations:completion:]'

有人可以帮助我了解代码中的错误之处吗?

1 个答案:

答案 0 :(得分:0)

当您第二次致电currentViewController时,您的self可能尚未完全添加到moveViewController:toViewController中。您可以在方法的开头放置这样的语句,以查看我的假设是否正确:

NSAssert([self.childViewControllers containsObject:currentViewController], @"The currentViewController: %@ is not a childViewController, here are the current childViewControllers: %@", currentViewController, self.childViewControllers);

编辑: 如果此假设不正确,则可能需要编辑您的问题以包含您对该方法的调用以获取进一步的上下文