Use a CAKeyframeAnimation
on the view's layer, instead of using +[UIView animateWithDuration:...]
.
First, you may need to add the QuartzCore framework to your target. If you don't know how to do that, read How to "add existing frameworks" in Xcode 4? Also add #import <QuartzCore/QuartzCore.h>
to your app's .pch
header file.
Now you can animate the view along a path. First, create a UIPath for the path you want the view to follow. This example will move the view to the right 50 points, and then down 100 points:
CGPoint position = self.playerOneImage.layer.position;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:position];
position.x += 50; [path addLineToPoint:position];
position.y += 100; [path addLineToPoint:position];
Next, create a CAKeyframeAnimation
that will animate the position property along that path:
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.duration = 1.0f;
animation.path = path.CGPath;
animation.calculationMode = kCAAnimationPaced;
There are lots of options for changing the speed at which the layer moves along the path - check the docs.
Next, you have to set the layer's position to the final position, where you want it to be after the animation is over. It seems weird, but it's absolutely necessary:
// Important: you must actually set the layer's position!
// Otherwise the animation will put it back at the start
// when the animation ends. You should set the layer's
// final position, then add the animation.
self.playerOneImage.layer.position = position;
Finally, add the animation to the layer:
[self.playerOneImage.layer addAnimation:animation forKey:@"position"];
And you're done.
All together for easy cut/paste:
CGPoint position = self.playerOneImage.layer.position;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:position];
position.x += 50; [path addLineToPoint:position];
position.y += 100; [path addLineToPoint:position];
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.duration = 1.0f;
animation.path = path.CGPath;
animation.calculationMode = kCAAnimationPaced;
// Important: you must actually set the layer's position!
// Otherwise the animation will put it back at the start
// when the animation ends. You should set the layer's
// final position, then add the animation.
self.playerOneImage.layer.position = position;
[self.playerOneImage.layer addAnimation:animation forKey:@"position"];