how to force view controller to stay in portrait m

2019-08-28 04:28发布

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?

3条回答
戒情不戒烟
2楼-- · 2019-08-28 05:13

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;
}
查看更多
Root(大扎)
3楼-- · 2019-08-28 05:21

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
查看更多
霸刀☆藐视天下
4楼-- · 2019-08-28 05:23

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?

查看更多
登录 后发表回答