以上都不适合我,我设法做我自己的自定义推/拉动画,它就像一个魅力。
首先,添加这个实现 Push 场景的类
class PushAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
// start the toView to the right of the screen
var frame = toView.frame
frame.origin.x = container.frame.width
toView.frame = frame
// add the both views to our view controller
container.addSubview(toView)
container.addSubview(fromView)
// get the duration of the animation
let duration = self.transitionDuration(using: transitionContext)
// perform the animation!
UIView.animate(withDuration: duration, animations: {
var frame = fromView.frame
frame.origin.x = -container.frame.width
fromView.frame = frame
toView.frame = container.bounds
}, completion: { _ in
// tell our transitionContext object that we've finished animating
transitionContext.completeTransition(true)
})
}
}
然后添加这个实现pop场景的类
import Foundation
import UIKit
class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// get reference to our fromView, toView and the container view that we should perform the transition in
let container = transitionContext.containerView
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!
// set up from 2D transforms that we'll use in the animation
let offScreenRight = CGAffineTransform(translationX: container.frame.width, y: 0)
// start the toView to the right of the screen
var frame = toView.frame
frame.origin.x = -container.frame.width
toView.frame = frame
// add the both views to our view controller
container.addSubview(toView)
container.addSubview(fromView)
// get the duration of the animation
let duration = self.transitionDuration(using: transitionContext)
// perform the animation!
UIView.animate(withDuration: duration, animations: {
fromView.transform = offScreenRight
toView.frame = container.bounds
}, completion: { _ in
// tell our transitionContext object that we've finished animating
transitionContext.completeTransition(true)
})
}
}
然后将此行添加到您的 viewDidLoad 方法以更改默认 NavigationController Delegate
self.navigationController?.delegate = self
看看魔法:)