Rashmi Ranjan mallick Rashmi Ranjan mallick - 5 months ago 86
iOS Question

How to force view controller orientation in iOS 8?

Before iOS 8, we used below code in conjunction with supportedInterfaceOrientations and shouldAutoRotate delegate methods to force app orientation to any particular orientation. I used below code snippet to programmatically rotate the app to desired orientation. Firstly, I am changing the status bar orientation. And then just presenting and immediately dismissing a modal view rotates the view to desired orientation.

[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:YES];
UIViewController *c = [[UIViewController alloc]init];
[self presentViewController:vc animated:NO completion:nil];
[self dismissViewControllerAnimated:NO completion:nil];


But this is failing in iOS 8. Also, I have seen some answers in stack overflow where people suggested that we should always avoid this approach from iOS 8 onwards.

To be more specific, my application is a universal type of application. There are three controllers in total.


  1. First View controller- It should support all orientations in iPad and only portrait (home button down) in iPhone.

  2. Second View controller- It should support only landscape right in all conditions

  3. Third View controller- It should support only landscape right in all conditions



We are using navigation controller for page navigation. From the first view controller, on a button click action, we are pushing the second one on stack. So, when the second view controller arrives, irrespective of device orientation, the app should lock in landscape right only.

Below is my
shouldAutorotate
and
supportedInterfaceOrientations
methods in second and third view controller.

-(NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskLandscapeRight;
}

-(BOOL)shouldAutorotate {
return NO;
}


Is there any solution for this or any better way of locking a view controller in particular orientation for iOS 8. Please help!!

Answer

For iOS 7 & 8:

Objective-C:

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

Swift:

let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")

Just call it in - viewDidAppear: of the presented view controller.