IPhone – allow landscape orientation on just one viewcontroller

cocoa-touchiphone

I have a navigation-based application in which I would like just one of the viewcontrollers to support landscape orientation. For that viewcontroller (vc1), in shouldAutorotate, I am returning YES for all orientations and in the other controllers I am returning YES only for portrait mode

But even then if the device is in landscape mode and I go to the next screen from vc1, the next screen also comes up rotated in landscape mode. I assumed that if I return a YES only for portrait mode, the screen should show up only in portrait.

Is this the expected behavior? How do I achieve what I am looking for?

Thanks.

Best Answer

You can't support the landscape orientation only for one of the viewcontrollers if you use shouldAutorotateToInterfaceOrientation method of UIViewController.
You have only two choice whether all viewcontrollers support the landscape or no viewcontrollers support it.

If you want to support the landscape only for one, You need to detect device rotation and manually rotate views in the viewcontroller.
You can detect the device rotation by using Notification.

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

Then, you can rotate your views when you detect the device rotation.

- (void)didRotate:(NSNotification *)notification {
    UIDeviceOrientation orientation = [[notification object] orientation];

    if (orientation == UIDeviceOrientationLandscapeLeft) {
        [xxxView setTransform:CGAffineTransformMakeRotation(M_PI / 2.0)];
    } else if (orientation == UIDeviceOrientationLandscapeRight) {
        [xxxView setTransform:CGAffineTransformMakeRotation(M_PI / -2.0)];
    } else if (orientation == UIDeviceOrientationPortraitUpsideDown) {
        [xxxView setTransform:CGAffineTransformMakeRotation(M_PI)];
    } else if (orientation == UIDeviceOrientationPortrait) {
        [xxxView setTransform:CGAffineTransformMakeRotation(0.0)];
    }
}