- (void)transitionFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^ __nullable)(void))animations completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(5_0);复制代码交换两个子视图控制器的位置(由于添加的顺序不同,所以子试图控制器在父视图控制器中存在层次关系)
fromViewController:当前显示的子试图控制器,将被替换为非显示状态 toViewController:将要显示的子视图控制器 duration:交换动画持续的时间,单位秒 options:动画的方式 animations:动画Block completion:完成后执行的Block复制代码切换子视图控制器
- (void)viewCotrollerChange:(UISegmentedControl *)sender { if (sender.selectedSegmentIndex == _selectedIndex) { return; } _selectedIndex = sender.selectedSegmentIndex; if (sender.selectedSegmentIndex == 0) { [self changeToNormalImageView]; }else if (sender.selectedSegmentIndex == 1) { [self changeToVRImageView]; }else if (sender.selectedSegmentIndex == 2) { [self changeToVideView]; }}- (void)changeToNormalImageView { [self addChildViewController:self.normalImageVC]; UIViewController *oldViewController = _currentViewController; [self transitionFromViewController:_currentViewController toViewController:self.normalImageVC duration:0.5 options:UIViewAnimationOptionTransitionNone animations:^{ } completion:^(BOOL finished) { if (finished) { [_normalImageVC didMoveToParentViewController:self]; [_currentViewController willMoveToParentViewController:nil]; [_currentViewController removeFromParentViewController]; _currentViewController = self.normalImageVC; }else { _currentViewController = oldViewController; } }];}复制代码
在写的过程中出现过一个很奇怪的问题,切换到normalImageView的时候,transitionFromViewController的completion的回调 finished一直为NO;导致子视图控制器的切换失败。
经过多次调试后发现,normalImageVC的viewWillAppear里有个刷新,每次切换到该子视图控制器的时候都会刷新,导致切换失败。增加duration的动画时间效果不明显,因为用户可以疯狂的点击Segment进行切换。 最终通过修改normalImageVC的viewWillAppear方法,不让他刷新,解决了这个问题,这里做一个简单的记录。