基本上我只是在imageView上添加一个简单的旋转动画,它是UICollectionViewCell的子视图,动画效果很好,但是当我滚动集合视图并向后滚动时,动画就停止了。如何解决这个问题呢? 这是我添加到imageView的内容。
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Double.pi
rotationAnimation.duration = 2.0
rotationAnimation.repeatCount = .infinity
view.layer.add(rotationAnimation, forKey: nil)
答案 0 :(得分:1)
为了避免滚动的影响,需要使用Runloop及其commonModes,使用CADisplayLink制作动画可以做到:
private var _displayLinkForRotation:CADisplayLink?
var displayLinkForRotation:CADisplayLink {
get{
if _displayLinkForRotation == nil {
_displayLinkForRotation = CADisplayLink(target: self, selector: #selector(excuteAnimations))
_displayLinkForRotation?.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
}
return _displayLinkForRotation!
}
}
func excuteAnimations() {
//This function will be called 60 times per second.
//According to your question, you have 2 seconds to rotate the view to 180 angle. So we rotate 90 angle per second here.
//self.view could be replaced by another view you want to rotate.
self.view.transform = self.view.transform.rotated(by: 90.0 / 60.0 / 180.0 * CGFloat.pi)
let angle = atan2(self.view.transform.b, self.view.transform.a) * (45.0/atan(1.0))
if (round(angle) >= 180.0) { //Stop when rotated 180 angle
self.displayLinkForRotation.isPaused = true
}
}
开始动画:
self.displayLinkForRotation.isPaused = false
摧毁它:
self.displayLinkForRotation.invalidate()
_displayLinkForRotation = nil
答案 1 :(得分:0)
因为您没有为初始化rotationAnimation时使用的动画添加键 改变行
view.layer.add(rotationAnimation, forKey: nil)
到
view.layer.add(rotationAnimation, forKey: "transform.rotation")
希望有所帮助