bdunagan

Brian Dunagan

February 16 2010
iPhone Tip: Rotating UIView

The iPhone OS’s accelerometer tells me the exact x, y, and z orientation of an iPhone or iPod Touch. Which is freakin’ awesome. To demonstrate how easy it is to leverage, I wrote a bit of code to rotate a UILabel in a simple Utility app. The controller sets itself as the delegate for UIAccelerometer and then responds to the selector accelerometer:didAccelerate:. I started by simply using the exact rotation, but that resulted in a very wobbly text label; so, I added a bit of rounding and animation to dampen it.

// add UIAccelerometerDelegate as a delegate to the controller
// add a UILabel to the XIB and hook it up to the controller
// add QuartzCore framework

// MainViewController.h
@interface MainViewController : UIViewController <UIAccelerometerDelegate> {
	IBOutlet UILabel *textLabel;
}
@end

// MainViewController.m
#import "MainViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		// Set this controller as the accelerometer's delegate.
		[[UIAccelerometer sharedAccelerometer] setDelegate:self];
    }
    return self;
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
	// Get the rotation in radians.
	CGFloat rotation = (atan2(acceleration.x, acceleration.y) + M_PI);
	// Dampen it a bit.
	float div = 48 / (2 * M_PI);
	rotation = (int)(rotation * div) / div;
	// Animate the movement a bit.
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.2];
	textLabel.layer.transform = CATransform3DMakeRotation(rotation, 0, 0, 1);
	[UIView commitAnimations];
}

@end
iPhone Tip: Capturing a Shake Event Cocoa Tip: Continuous Updates and Bindings
LinkedIn GitHub Email