4
votes

Here's my view controller code for the view controller that I only want to display in portrait orientation...

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

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

- (BOOL)shouldAutorotate {
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

and here's how I'm presenting it...

MyViewController *myVC = [[MyViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:myVC];
[self presentViewController:nav animated:YES completion:nil];

If the device is in landscape orientation and the view controller is presented, it correctly autorotates to portrait orientation. But if you rotate the device after it's displayed, it autorotates to whatever orientation the device is in. I want to prevent autorotation after its displayed and force only portrait orientation for just this one view controller. This is an iOS8-only app.

Thanks in advance for your wisdom!

2
did you try this (the second answer that uses the app delegate): stackoverflow.com/questions/12520030/…Hakim
@matt, that doesn't fix it, it still autorotates. I updated my question to reflect that change, however.BeachRunnerFred
@BeachRunnerFred Thanks for waking me up to what was really going on; I didn't read your code closely enough, but now I see the problem.matt

2 Answers

5
votes

The problem is that you are setting the supportedInterfaceOrientations for the wrong object. You have implemented supportedInterfaceOrientations in MyViewController. But look at your code:

MyViewController *myVC = [[MyViewController alloc] init];
UINavigationController *nav = 
    [[UINavigationController alloc] initWithRootViewController:myVC];
[self presentViewController:nav animated:YES completion:nil];

nav is the presented view controller - not MyViewController. So nav, the UINavigationController, governs whether we will rotate - not MyViewController.

So, give nav a delegate in which you implement navigationControllerSupportedInterfaceOrientations: - and all will be well.

1
votes

You are returning the wrong value in your supportedInterfaceOrientations method.

You need to return UIInterfaceOrientationMaskPortrait.

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}