我刚刚从obj C搬到swift,我不知道为什么它不起作用,因为在它工作正常的情况下,请查看我的代码
这是我的代码
func addAnimationOnLayer( layer: CALayer, position: CGPoint, duration: TimeInterval, delay: TimeInterval, fromPosition: CGPoint, toPostion: CGPoint, key: String) {
layer.setAffineTransform(CGAffineTransform(translationX: position.x, y: position.y))
CATransaction.begin()
CATransaction.setCompletionBlock {
layer.setAffineTransform(CGAffineTransform(translationX: 0, y: 0))
}
let theAnimation = CABasicAnimation(keyPath: "transform.translation")
theAnimation.isRemovedOnCompletion = false
theAnimation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseInEaseOut)
theAnimation.fillMode = kCAFillModeForwards
theAnimation.duration = duration
theAnimation.beginTime = delay
theAnimation.fromValue = fromPosition
theAnimation.toValue = toPostion
layer.add(theAnimation, forKey: key)
CATransaction.commit()
}
我用这个
调用函数self.addAnimationOnLayer(layer: self.logoImage.layer, position: CGPoint(x: 0, y:100), duration: 0.8, delay: 0.1, fromPosition: CGPoint(x: 0,y: 100), toPostion: CGPoint(x: 0,y: 0), key: "logoStartAnimation")
答案 0 :(得分:2)
在致电CATransaction.begin()
之前,请尝试拨打CATransaction.flush()
。
您的代码将如下所示:
func addAnimationOnLayer( layer: CALayer, position: CGPoint, duration: TimeInterval, delay: TimeInterval, fromPosition: CGPoint, toPostion: CGPoint, key: String) {
layer.setAffineTransform(CGAffineTransform(translationX: position.x, y: position.y))
CATransaction.flush()
CATransaction.begin()
CATransaction.setCompletionBlock {
layer.setAffineTransform(CGAffineTransform(translationX: 0, y: 0))
}
let theAnimation = CABasicAnimation(keyPath: "transform.translation")
theAnimation.isRemovedOnCompletion = false
theAnimation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseInEaseOut)
theAnimation.fillMode = kCAFillModeForwards
theAnimation.duration = duration
theAnimation.beginTime = delay
theAnimation.fromValue = fromPosition
theAnimation.toValue = toPostion
layer.add(theAnimation, forKey: key)
CATransaction.commit()
}
尝试一下,让我知道,我之前遇到的问题是动画没有发生,因为之前剩下的动画有点遗留。