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

时间:2017-08-27 23:31:21

标签: ios swift uinavigationcontroller

我在UINavigationController堆栈中有推送和弹出事件的自定义动画过渡,我想将该自定义动画仅应用于特定的推送事件 - 例如,当推送RandomViewController44()或弹出RandomViewController27()时 - 不是每个在堆栈中推送和弹出。这是在UINavigationControllerDelegate,animator对象中,还是在push / pop中完成的?


代表

<title>.*?-\s*([^-]*)\s*- End<\/title>



动画制作者对象

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)
        })

    }

}

1 个答案:

答案 0 :(得分:1)

您可以在下面的委托方法中检查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
        }
    }
}

当此方法根据您的要求调用设置条件时,您需要检查来自和控制器