How to disable autorotation in iOS 8 for a particu

2019-02-20 16:43发布

问题:

-(BOOL)shouldAutorotate {

    return NO;

}

Above method works for one controller but when there are multiple viewControllers pushed on a stack.
I want a particular controller that should be displayed in portrait mode only.

- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {

}

I have used above method suggested on stack overflow for iOS 8 but it does not give desired result.

回答1:

First, use -supportedInterfaceOrientations instead of -shouldAutorotate. -shouldAutorotate should only be used when you must disallow autorotation based on factors determined at runtime. You know your view controller will always only support portrait mode, there is no runtime decision here.

Next, your navigation controller's delegate must implement the -navigationControllerSupportedInterfaceOrientations: method to return the result of calling -supportedInterfaceOrientations on the view controller at the top of the navigation stack.

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

An important caveat: A view controller pushed onto a navigation stack has no control over its initial interface orientation; that will always be the current interface orientation. What the above technique will do is prevent the interface from rotating to any orientation other than portrait while that view controller is displayed.