如何将UINavigationControllerDelegate中的自定义过渡动画应用于特定的推送和弹出事件?

问题描述:

我有一个UINavigationController堆栈中的推送和弹出事件的自定义动画转换,我想只将自定义动画应用于特定的推送事件 - 例如,推送RandomViewController44()或弹出RandomViewController27()时 - 并非每次推送并弹出堆栈。这是在UINavigationControllerDelegate,animator对象中,还是在push/pop点完成的?


委托如何将UINavigationControllerDelegate中的自定义过渡动画应用于特定的推送和弹出事件?

extension BaseViewController: UINavigationControllerDelegate { 

    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { 
     switch operation { 
     case .push: 
      return InAnimator() 
     case .pop: 
      return OutAnimator() 
     default: 
      return nil 
     } 
    } 

} 



动画制作对象

class InAnimator: NSObject, UIViewControllerAnimatedTransitioning { 

    let animationDuration = 0.5 

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { 
     return animationDuration 
    } 

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { 

     let screenHeight = UIScreen.main.bounds.height 
     let screenWidth = UIScreen.main.bounds.width 
     let containerView = transitionContext.containerView 
     let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) 

     containerView.addSubview(toViewController!.view) 

     toViewController!.view.frame = CGRect(x: screenWidth * -1, y: 0, width: screenWidth, height: screenHeight) 

     UIView.animate(withDuration: animationDuration, animations: { 
      toViewController!.view.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight) 
     }, completion: { finished in 
      let cancelled = transitionContext.transitionWasCancelled 
      transitionContext.completeTransition(!cancelled) 
     }) 

    } 

} 



呼叫推

func pushVC() { 
    navigationController?.pushViewController(randomViewController44(), animated: true) 
} 

您就可以在下面的委托方法的fromView和ToView控制器执行操作

extension BaseViewController: UINavigationControllerDelegate { 

    func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { 
     switch operation { 
     case .push: 
      if toVc is RandomViewController44{ 
       return InAnimator() 
      } 
      return nil 
     case .pop: 
      if RandomViewController27 is fromVC{ 
       return OutAnimator() 
      } 
      return nil 
     default: 
      return nil 
     } 
    } 
} 

你需要从检查和toView控制器时,被称为集条件,此方法按您的要求