我正在尝试旋转 UIImageView。旋转动画工作正常,但在图像结束时会返回到其原始方向。下面是我用来旋转它的扩展:
extension UIView {
func rotate(duration: CFTimeInterval = 1.0, degrees:Double, completionDelegate: AnyObject? = nil) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
let radians = CGFloat(degrees * M_PI / degrees)
rotateAnimation.toValue = CGFloat(radians)
rotateAnimation.duration = duration
if let delegate: AnyObject = completionDelegate {
rotateAnimation.delegate = delegate
}
self.layer.addAnimation(rotateAnimation, forKey: nil)
}
}
我已关闭自动布局。我错过了什么?
最佳答案
在直接核心动画中,您必须实际设置要设置动画的属性。单独制作动画仅显示效果,然后弹回到起始值。虽然设置 fillMode
和 removedOnCompletion
将在视觉上起作用,但图层上旋转属性的实际值仍然是原始值,而不是最终值您在动画的toValue
属性中指定。最终结果仅是视觉效果。
我建议您按照 Jan 的建议使用 UIView
动画函数,或者您可以在动画中显式设置该属性,例如:
func rotate(duration: CFTimeInterval = 1.0, degrees:Double, completionDelegate: AnyObject? = nil) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
let radians = CGFloat(degrees * M_PI / degrees)
rotateAnimation.toValue = CGFloat(radians)
rotateAnimation.duration = duration
if let delegate: AnyObject = completionDelegate {
rotateAnimation.delegate = delegate
}
self.layer.addAnimation(rotateAnimation, forKey: nil)
// Actually set the layer's property
self.layer.transform = CATransform3DMakeRotation(radians, 0.0, 0.0, 1.0)
}
关于iOS 快速旋转动画不固定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38405020/