Cocoa in the Shell

Rotating a view at 360°

I saw several times people struggling to do a 360° rotation on a UIView, so in this post I’ll show you how to do this, and you will see that, in fact, it’s very simple.

So let’s say we have a view named myView, we have several way to perform a rotation on it, in order to perform our 360° one, we will use the CABasicAnimation class, so don’t forget to link to the QuartzCore framework.

Here is the method that rotate our view :

-(void)perform360rotation
{
    CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    [anim setDuration:3.0f]; // Animation duration to 3 seconds
    [anim setAutoreverses:NO];
    [anim setRepeatCount:1]; // Perfrom animation 1 time
    [anim setFromValue:[NSNumber numberWithDouble:0.0f]];
    [anim setToValue:[NSNumber numberWithDouble:(M_PI * 2.0f)]];
    [[myView layer] addAnimation:anim forKey:@"my_rotation"];
}

When working with Core Animation, radians are used for angles, not degrees, if you really hate mathematics, 360° = 2π radians.

That’s all, your view is now able to rotate at 360° with only a few lines of code.

If you want the view to rotate around a specific axis you can specify it in the KeyPath parameter, like this :

CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];