restricting autorotation on certain views

2019-07-15 12:59发布

问题:

my app contains two table view controllers. in the first one i want the view to be able to be rotated left and right (in addition to the portrait mode), however in the second table view controller ( which i navigate to after tapping a cell from the first table) i want it to only be viewed in portrait mode. i tried this code but it didn't work, it keeps on rotating.

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL) shouldAutorotate {
    return NO;
}

note: i did actually enabled the left/right/portrait orientation from the Summary tab of the project target. any fix?

回答1:

Create a category for UINavigationController which include the following methods:

(Works both for iOS 6 and iOS 5)

- (BOOL)shouldAutorotate
    {
        return self.topViewController.shouldAutorotate;
    }

    - (NSUInteger)supportedInterfaceOrientations
    {
        return self.topViewController.supportedInterfaceOrientations;
    }

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
        return [self.topViewController shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
    }

Then implement these methods in your controllers

First:

- (BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations {
    if (RUNNING_IPAD) {
        return UIInterfaceOrientationMaskAll;
    }
    else {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    };
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    if (RUNNING_IPAD) {
        return YES;
    }
    else {
        return toInterfaceOrientation != UIInterfaceOrientationMaskPortraitUpsideDown;
    }
}

And Second:

- (BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
       return UIInterfaceOrientationMaskPortrait;
}

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

The rotation settings of the project should look like:



回答2:

Actually i found a solution for my problem:

-(BOOL)shouldAutorotate{
    return YES;
}

-(NSInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

this will restrict a view to portrait even if you toggled the left/right orientations in the Summary tab of the project's Traget.