klh63917
klh63917

Reputation: 13

ObjC disable ViewController rotation

I'm trying to disable screen rotation in just one ViewController. I'm using this to change screen orientation to portrait:

-(void)viewDidAppear:(BOOL)animated{
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}

and I'm disabling rotation like this:

- (BOOL)shouldAutorotate{
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

-(NSUInteger)navigationControllerSupportedInterfaceOrientations:(UINavigationController *)navigationController {
    return navigationController.topViewController.supportedInterfaceOrientations;
}

but it's not working. It rotates screen to portrait but it does't lock it, if I turn device it changes screen orientation.

Upvotes: 1

Views: 5495

Answers (2)

vien vu
vien vu

Reputation: 4337

You can try this code:

-(BOOL)shouldAutorotate
{
    return NO;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return NO;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

The above code will only work with UIViewControllers not UINavigationController stacks. If you are using a UINavigationController you should do the following:

Solution 1:

  1. Add to AppDelegate.h a variable: @property (nonatomic , assign) bool blockRotation;
  2. Add to AppDelegate.m function:

    - (UIInterfaceOrientationMask)application:(UIApplication *)application       supportedInterfaceOrientationsForWindow:(UIWindow *)window
     {
        if (self.blockRotation) {
            return UIInterfaceOrientationMaskPortrait;
     }
         return UIInterfaceOrientationMaskAll;
     }
    
  3. In controller want disable add this code:

    #import "AppDelegate.h"
    //Put to `viewDidload`
    AppDelegate* shared=[UIApplication sharedApplication].delegate;
    shared.blockRotation=YES;
    

Solution 2: you can follow this answer: Hanling orientation

Upvotes: 3

Piyush
Piyush

Reputation: 1544

If you want to temporarily disable automatic rotation, avoid manipulating the orientation masks to do this. Instead, override the shouldAutorotate method on the initial view controller. This method is called before performing any autorotation. If it returns NO, then the rotation is suppressed.

So you need to subclass 'UINavigationController', implement shouldAutorotate and use your navigation controller class in your storyboard.

- (BOOL)shouldAutorotate
{
    id currentViewController = self.topViewController;

    if ([currentViewController isKindOfClass:[DetailViewController class]])
        return NO;

    return YES;
}

Upvotes: 0

Related Questions