Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a view or label in x direction using CABasicAnimation in iPhone

Tags:

iphone

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.

like image 378
rkb Avatar asked Oct 12 '09 16:10

rkb


2 Answers

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.

like image 182
Alex Avatar answered Oct 16 '22 01:10

Alex


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
like image 39
mihai Avatar answered Oct 16 '22 01:10

mihai