使用Rob&Q i的完美答案,这是简化的Swift代码,对.push和.pop使用相同的淡入淡出动画:
extension YourViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationControllerOperation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
class FadeAnimation: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
if let vc = toViewController {
transitionContext.finalFrame(for: vc)
transitionContext.containerView.addSubview(vc.view)
vc.view.alpha = 0.0
UIView.animate(withDuration: self.transitionDuration(using: transitionContext),
animations: {
vc.view.alpha = 1.0
},
completion: { finished in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
} else {
NSLog("Oops! Something went wrong! 'ToView' controller is nill")
}
}
}
return FadeAnimation()
}
}
不要忘记在YourViewController的viewDidLoad()方法中设置委托:
override func viewDidLoad() {
self.navigationController?.delegate = self
}