jamztang
8/3/2012 - 4:48 AM

Properly handle custom rotation animations in both iOS 4 and iOS 5

Properly handle custom rotation animations in both iOS 4 and iOS 5

@interface YourViewController ()
@property (unsafe_unretained, nonatomic) UIInterfaceOrientation fromInterfaceOrientation;
@end

@implementation YourViewController
@synthesize fromInterfaceOrientation;

#pragma mark Rotations for iOS 5

- (void)viewWillLayoutSubviews {

    if (self.fromInterfaceOrientation == UIDeviceOrientationUnknown) {
        // willRotateToInterfaceOrientation has never been called in iOS5.
        // We manually call the rotations callback to correctly layout subviews
        UIInterfaceOrientation interfaceOrientation = self.interfaceOrientation;
        [self willRotateToInterfaceOrientation:interfaceOrientation duration:0];
        [self willAnimateRotationToInterfaceOrientation:interfaceOrientation duration:0];
    }
}

#pragma mark Rotations

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return YES;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    CGSize bounds = self.view.frame.size;
    self.fromInterfaceOrientation = self.interfaceOrientation;

    // Add or remove subviews from the current view hierarchy here...
    if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
    } else {
    }
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    CGSize bounds = self.view.frame.size;

    if ((UIInterfaceOrientationIsPortrait(toInterfaceOrientation) && (bounds.width > bounds.height))
        || (UIInterfaceOrientationIsLandscape(toInterfaceOrientation) && (bounds.width < bounds.height))) {
        
        // Fix the expected width and height.
        bounds = CGSizeMake(self.view.frame.size.height, self.view.frame.size.width);
    }

    // Modify the subviews to target frame here...
    // Anything will be automatically animated because
    // this method is called inside an animation block 
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    // Add or remove subviews from the current view hierarchy
    // after rotation animation ends.
}

@end