Reputation: 627
Basically I just add a simple rotate animation on an imageView which is a subview of UICollectionViewCell, the animation works fine, but when I scroll the collection view and scroll back, the animation just stoped. How to solve this problem? This is what I added to the 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)
Upvotes: 0
Views: 362
Reputation: 1325
Because you have not added key for animation, which you used when initialising rotationAnimation change line
view.layer.add(rotationAnimation, forKey: nil)
to
view.layer.add(rotationAnimation, forKey: "transform.rotation")
Hope it helps
Upvotes: 0
Reputation: 6648
To avoid scrolling's influence, need to use Runloop and its commonModes, making animation with CADisplayLink can do it:
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
}
}
To start animation:
self.displayLinkForRotation.isPaused = false
To destroy it:
self.displayLinkForRotation.invalidate()
_displayLinkForRotation = nil
Upvotes: 1