J
Published on
· Last modified on
· Public

如何自定义UINavigationController的push和pop动画

在iOS7之后

  • UINavigationControllerDelegate新增了如下方法来返回动画控制对象
 
  - (id<UIViewControllerAnimatedTransitioning>)navigationController:
                                  animationControllerForOperation:
                                               fromViewController:
                                                 toViewController:
 
  • 要实现自定义的动画效果 只要在上述方法中返回一个实现了 <UIViewControllerAnimatedTransitioning> 协议的对象
 
  - (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
  // return animation duration here.
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
  // implement animation here
}
 

示例

实现协议 <UIViewControllerAnimatedTransitioning>

 
  - (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
  return 0.25
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
  // Get the two view controllers
  UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];

  UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

  // where the animation has to happen
  UIView *containerView = [transitionContext containerView];

  [containerView addSubview:fromVC.view];
  [containerView addSubview:toVC.view];

  toVC.view.alpha = 0.0;
  // Perform the animation
  [UIView animateWithDuration:[self transitionDuration:transitionContext]
                        delay:0
                      options:0
                   animations:^{
                       toVC.view.alpha = 1.f;
                   }
                   completion:^(BOOL finished) {
                       [fromVC.view removeFromSuperview];
                       [transitionContext completeTransition:YES];
                   }];

}
 

然后实现协议 UINavigationControllerDelegate

 
  - (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC {

    return [TestTransition new];
}
 

最后设置UINavigationController的代理

 
  - (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self) {
        _navDelegate = [SCNavControllerDelegate new];
        self.delegate = _navDelegate;
    }
    return self;
}
 

此时使用pushViewController方法 动画效果已经被改变

有的时候需要将UINavigationBar也一起移动

  • 要将UINavigationBar随view一起移动 使用系统提供的这些不太好实现
  • 另外一种思路是可以直接重写push和pop方法 把整个控制器移走 后面放一个截图便可

示例

E
Published on

我们公司的app为了方便在navigation bar上加东西,使用的是自绘UINavigationBar,直接添加到vc的view上,顺便有了将navigation bar 一起移动的特性~

Sign in or Sign up Leave Comment