iOS 7. Change page orientation only for one view controller

alexxjk picture alexxjk · Nov 11, 2013 · Viewed 7.2k times · Source

I have iPhone application that supports only Portrait orientation. I want to add to my project view controller that will support only Landscape orientation? Is it possible? If yes how could I achieve that?

I have tried to crate category file like this:

@implementation UINavigationController (Rotation_IOS7)

-(BOOL)shouldAutorotate
    {

        return YES;

    }

    -(NSUInteger)supportedInterfaceOrientations
    {

      return UIInterfaceOrientationMaskLandscape;

    }

If I do this I get this error: Terminating app due to uncaught exception UIApplicationInvalidInterfaceOrientation, reason: Supported orientations has no common orientation with the application, and shouldAutorotate is returning YES

Answer

Hanton picture Hanton · Dec 11, 2014

I've tried this and it works: http://www.sebastianborggrewe.de/only-make-one-single-view-controller-rotate/

First, add these code to your AppDelegat class.

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
// Get topmost/visible view controller
UIViewController *currentViewController = [self topViewController];

// Check whether it implements a dummy methods called canRotate
if ([currentViewController respondsToSelector:@selector(canRotate)]) {
    // Unlock landscape view orientations for this view controller
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

// Only allow portrait (standard behaviour)
return UIInterfaceOrientationMaskPortrait;
}

- (UIViewController*)topViewController {
  return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
  if ([rootViewController isKindOfClass:[UITabBarController class]]) {
    UITabBarController* tabBarController = (UITabBarController*)rootViewController;
    return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
  } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
    UINavigationController* navigationController = (UINavigationController*)rootViewController;
    return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
  } else if (rootViewController.presentedViewController) {
    UIViewController* presentedViewController = rootViewController.presentedViewController;
    return [self topViewControllerWithRootViewController:presentedViewController];
  } else {
    return rootViewController;
  }
}

Then, in your landscape view controller, add this method

- (void)canRotate { }