Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force portrait mode when dismissing a presented view controller

I have a presented view-controller that is supporting all interface orientations. However, the presenting view controller only should support portrait mode.

So far so good.

However, in iOS8, when I dismiss the view controller WHILE in landscape mode, landscape mode stays. And since I have shouldAutorotate set to NO it an never rotate back.

Question is, how can I force the presenting VC to return to portrait?

I currently have this workaround implemented:

- (BOOL)shouldAutorotate
{
  if ([self interfaceOrientation] != UIInterfaceOrientationPortrait)
  {
    return YES;
  }
  else
  {
    return NO;
  } 
}

It allows to move the device into portrait and it will stay here, since after it's portrait autorotate is disable.

But it looks ugly until the user rotates his phone.

How to force it?

like image 811
user3589281 Avatar asked Sep 20 '14 16:09

user3589281


1 Answers

We had the exactly same problem. You can rotate it programmatically by the code -

if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait) {
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}

There are 2 possible options -

1) before you dismiss the presented viewController, rotate to portrait if needed

2) after you dismiss, rotate to portrait in the "viewDidAppear" of the presenting viewController.

One issue with this, is that you can't pass a completion block, but you can use the next callback in iOS8:

-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    if (self.needToDismissAfterRotatation)
        self.needToDismissAfterRotatation = NO;
        [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
            // dismiss
        }];
    }
}

By the way, in iOS8 apple did a huge change in the way the screen rotates, when the app rotates, the screen rotates, and all the elements in the UIWindow rotates as well, this is why when the presented viewController rotates to landscape, also the presenting viewController rotates, even if it only supports portrait...

We struggled with this issue for many days, finally we came up with a solution to put the presented viewController in a new UIWindow, and this way it keeps the presenting viewController in portrait all the time

example project for that: "modalViewController" in UIWindow


like image 78
oren Avatar answered Oct 02 '22 01:10

oren