我按照以下指南来实现翻牌动画: https ://www.raywenderlich.com/110536/custom-uiviewcontroller-transitions
这是我的动画师的代码(与指南上的相同):
import UIKit
class FlipCardAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var originFrame = CGRect.zero
var cardView = UIView()
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.6
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey),
let containerView = transitionContext.containerView(),
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else {
return
}
let initialFrame = originFrame
let finalFrame = transitionContext.finalFrameForViewController(toVC)
let snapshot = toVC.view.snapshotViewAfterScreenUpdates(true)
snapshot.frame = initialFrame
snapshot.layer.cornerRadius = 25
snapshot.layer.masksToBounds = true
containerView.addSubview(toVC.view)
containerView.addSubview(snapshot)
toVC.view.hidden = true
perspectiveTransformForContainerView(containerView)
snapshot.layer.transform = yRotation(M_PI_2)
let duration = transitionDuration(transitionContext)
UIView.animateKeyframesWithDuration(
duration,
delay: 0,
options: .CalculationModeCubic,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1/3, animations: {
fromVC.view.layer.transform = self.yRotation(-M_PI_2)
})
UIView.addKeyframeWithRelativeStartTime(1/3, relativeDuration: 1/3, animations: {
snapshot.layer.transform = self.yRotation(0.0)
})
UIView.addKeyframeWithRelativeStartTime(2/3, relativeDuration: 1/3, animations: {
snapshot.frame = finalFrame
})
},
completion: { _ in
toVC.view.hidden = false
snapshot.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled())
})
}
func yRotation(angle: Double) -> CATransform3D {
return CATransform3DMakeRotation(CGFloat(angle), 0.0, 1.0, 0.0)
}
func perspectiveTransformForContainerView(containerView: UIView) {
var transform = CATransform3DIdentity
transform.m34 = -0.002
containerView.layer.sublayerTransform = transform
}
}
问题:我只看到视图在它的边缘翻转,然后什么也没有!屏幕消失了,我根本看不到目标视图控制器视图。虽然我可以看到它的函数 viewDidLoad 确实被调用(添加了打印调试)。由于某种原因,只有前 1/3 的动画有效,然后我什么都看不到。