views:

93

answers:

1

How would I do this, all I want to do is rotate a UIImageView depending on the orientation of the iPhone.

+2  A: 

You can do this through IB, to get an app with a portrait and a landscape layout, or you can do it programmatically. This is about the programmatic way.

To get notifications on the change of orientation, use

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self
                selector:@selector(orientationChanged)
                name:UIDeviceOrientationDidChangeNotification
                object:nil];

and add a function like this (note this is copypasted from a project and a lot of lines are left out, you will need to tune the transformation to your specific situation)

-(void)orientationChanged
{
    UIDeviceOrientation o = [UIDevice currentDevice].orientation;

    CGFloat angle = 0;
    if ( o == UIDeviceOrientationLandscapeLeft ) angle = M_PI/2.0f;
    else if ( o == UIDeviceOrientationLandscapeRight ) angle = -M_PI/2.0f;
    else if ( o == UIDeviceOrientationPortraitUpsideDown ) angle = M_PI;

    [UIView beginAnimations:@"rotate" context:nil];
    [UIView setAnimationDuration:0.7];
    self.rotateView.transform = CGAffineTransformRotate(
                                CGAffineTransformMakeTranslation(
                                    160.0f-self.rotateView.center.x,
                                    240.0f-self.rotateView.center.y
                                ),angle);
    [UIView commitAnimations];
}

When you're done, stop the notifications like so:

[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] removeObserver:self];
mvds
Hmm, this doesn't seem to work perfectly for me as it won't rotate just the UIImageView/UIView which is inside another UIView. Instead it rotates the whole UIView not just the sub-view.
Joshua
then make `self.rotateView` just the sub-view you want to have rotated.
mvds