how to force view controller to stay in portrait mode?

倾然丶 夕夏残阳落幕 提交于 2020-01-25 12:00:08

问题


I have an iOS application with storyboard. I want my last viewcontroller to stay always in portrait mode. I've been reading and I found that since

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation

is deprecated I should use other methods like

-(BOOL)shouldAutorotate  
-(NSInteger)supportedInterfaceOrientations
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation

but i have tried so many combinations of this methods and I have not been able to do it. So please can someone tell me the correct way?


回答1:


Since your UIViewController is embedded in a UINavigationController it'll never get called unless you forward on the calls yourself. (A bit of a flaw in UINavigationController in my opinion)

Subclass UINavigationController like this:

@interface RotationAwareNavigationController : UINavigationController

@end

@implementation RotationAwareNavigationController

-(NSUInteger)supportedInterfaceOrientations {
    UIViewController *top = self.topViewController;
    return top.supportedInterfaceOrientations;
}

-(BOOL)shouldAutorotate {
    UIViewController *top = self.topViewController;
    return [top shouldAutorotate];
}

@end



回答2:


If you have UIViewControllers within other UIViewControllers (ie a UINavigationController or a UITabBarController), you will need to proxy those messages to the child object you're implementing this behavior for.

Have you set a breakpoint in your implementations to be sure your view controller is being queried?




回答3:


In AppDelegate:

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    NSUInteger orientations = UIInterfaceOrientationMaskAllButUpsideDown;

    if(self.window.rootViewController) {
        UIViewController *presentedViewController = [[(UINavigationController *)self.window.rootViewController viewControllers] lastObject];
        orientations = [presentedViewController supportedInterfaceOrientations];
    }

    return orientations;
}

In Your ViewController:

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}


来源:https://stackoverflow.com/questions/16720968/how-to-force-view-controller-to-stay-in-portrait-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!