I am using the following code to move a label from one position to another in x direction
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
theAnimation.duration=1;
theAnimation.repeatCount=1;
theAnimation.autoreverses=NO;
theAnimation.fromValue=[NSNumber numberWithFloat:0];
theAnimation.toValue=[NSNumber numberWithFloat:80];
[lbl.layer addAnimation:theAnimation forKey:@"animateLayer"];
But in this case at the end of the animation the label shifts back to its original position. How to make sure it stays at the position where it is moved.
Is there any good way to do it without using timer and changing the coordinates on our own.
After the animation completes, it is removed. That's why it snaps back. Add this to your animation:
theAnimation.removedOnCompletion = NO;
theAnimation.fillMode = kCAFillModeForwards;
This will prevent the animation from being removed, and tells the animation to remain in its final state upon completion.
There are 2 items that need updating here. The presentation layer and the model. CABasicAnimation changes only the presentation layer and never updates the model. So when the presentation layer from the animation finishes, it goes away and you see the view with the values from the model. You just have to update the model with the new value when the animation is done.
[layer setValue:toValue forKeyPath:keyPath];
have a look at a utility i wrote to help out with exactly with this, HMBasicAnimation http://hellomihai.wordpress.com/2014/09/02/hmbasicanimation-utility/
usage:
[HMBasicAnimation doAnimation:myView.layer // layer youre updating
toValue:myView.frame.size.width/2 // your value
duration:1.5 // duration
delaySeconds:1 // animation delay (good for chaining animations
keyPath:HMBasicAnimation_TRANSLATION_X]; // what you're changing, several available
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With