Reputation: 469
i am trying to animate an image on select of UITableViewCell, the image is a child of the UITableViewCell, but it’s returning back to its default state after rotating, this is my code below.
override func setSelected(_ selected: Bool, animated: Bool) {
if selected {
super.setSelected(selected, animated: animated)
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = (180.0 * CGFloat(M_PI)) / 180.0
rotationAnimation.duration = 0.45
self.updownImage.layer.add(rotationAnimation, forKey: nil)
}
// Configure the view for the selected state
}
Upvotes: 0
Views: 296
Reputation: 131398
You should set the layer's transform to the final value immediately before adding the animation.
An CABasicAnimation does not actually change the layer's properties, it just sets up the layer's "presentation layer" to show what the change would look like. Once the animation is complete the presentation layer is hidden and the layer reverts to its non-animated state. By setting the layer to it's final state before adding the animation, the layer is revealed in it's final state when the animation is removed.
It's a very simple change to your existing code:
override func setSelected(_ selected: Bool, animated: Bool) {
if selected {
super.setSelected(selected, animated: animated)
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
//Put the angle in a constant so we can use to create a transform
let angle = (180.0 * CGFloat(M_PI)) / 180.0
rotationAnimation.toValue =
rotationAnimation.duration = 0.45
self.updownImage.layer.add(rotationAnimation, forKey: nil)
//Create a transform for our rotation
let transform = CATransform3DMakeRotation(angle, 0, 0, 1)
//install the transform on the layer so the change is active after
//the animation completes
layer.transform = transform
}
}
Upvotes: 1