【发布时间】:2016-07-19 23:20:14
【问题描述】:
我想要一个层的行为如下:
相反,它的行为是这样的:
卡片翻转动画是由两个CABasicAnimations 应用在一个CAAnimationGroup 中创建的。发生不正确的旋转效果是因为CALayer 属性更改的隐式动画首先运行,然后我在CABasicAnimation 中指定的动画运行。如何阻止隐式动画运行,以便仅运行我指定的动画?
以下是相关代码:
class ViewController: UIViewController {
var simpleLayer = CALayer()
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
self.view.addGestureRecognizer(tap)
simpleLayer.frame = CGRect(origin: CGPoint(x: view.bounds.width / 2 - 50, y: view.bounds.height / 2 - 50), size: CGSize(width: 100, height: 100))
simpleLayer.backgroundColor = UIColor.blackColor().CGColor
view.layer.addSublayer(simpleLayer)
}
func handleTap() {
let xRotation = CABasicAnimation(keyPath: "transform.rotation.x")
xRotation.toValue = 0
xRotation.byValue = M_PI
let yRotation = CABasicAnimation(keyPath: "transform.rotation.y")
yRotation.toValue = 0
yRotation.byValue = M_PI
simpleLayer.setValue(M_PI, forKeyPath: "transform.rotation.y")
simpleLayer.setValue(M_PI, forKeyPath: "transform.rotation.x")
let group = CAAnimationGroup()
group.animations = [xRotation, yRotation]
group.duration = 0.6
group.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
simpleLayer.addAnimation(group, forKey: nil)
}
}
【问题讨论】:
-
如果
setValue(_:forKeyPath:)被Core Animation 监控以激活隐式动画,我实际上并不肯定。如果你用CATransactionthat disables actions 包围这两个函数调用,这能解决问题吗? -
谢谢你,@LucasTizma!那是正确的代码。我在下面的答案中对其进行了全面描述。
-
我收到了对原始问题的反对票,所以现在的值为“-1”。我不知道为什么我收到了反对票。如果反对者可以发表评论,我很乐意解决他或她的担忧。这并不像看起来那样具体。这个问题普遍适用。除非您添加代码以禁用隐式动画,否则 CAAnimationGroup 不会按预期运行。
标签: ios swift core-animation calayer cabasicanimation