Force portrait orientation while pushing from landscape View Controller

别来无恙 提交于 2019-11-27 12:39:27

I solved this by adding following lines in ViewDidLoad

UIViewController *c = [[UIViewController alloc]init];
[self presentViewController:c animated:NO completion:nil];
[self dismissViewControllerAnimated:NO completion:nil];

First, you need to create a category:

UINavigationController+Rotation_IOS6.h

#import <UIKit/UIKit.h>

@interface UINavigationController (Rotation_IOS6)

@end

UINavigationController+Rotation_IOS6.m:

#import "UINavigationController+Rotation_IOS6.h"

@implementation UINavigationController (Rotation_IOS6)

-(BOOL)shouldAutorotate
{
    return [[self.viewControllers lastObject] shouldAutorotate];
}

-(NSUInteger)supportedInterfaceOrientations
{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

@end

Then, you implement these methods in your class that you want to be only landscape:

- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

In case you're using a UITabBarController, just replace the UINavigationController for UITabBarController. This solution worked nice for me after a long search! I was in the same situation as you are now!

EDIT

So, I saw your sample. You need to make some changes. 1 - Create a new class for the UINavigationController category. Name the class UINavigationController+Rotation_IOS6 (.h and .m) 2 - You don't need to implement the method preferredInterfaceOrientationForPresentation. Your category should look like this:

#import "UINavigationController+Rotation_IOS6.h"

@implementation UINavigationController (Rotation_IOS6)

-(BOOL)shouldAutorotate
{
    return [[self.viewControllers lastObject] shouldAutorotate];
}

-(NSUInteger)supportedInterfaceOrientations
{
    return [[self.viewControllers lastObject] supportedInterfaceOrientations];
}

@end

3 - In the class you want to rotate only in landscape, include this in the implementation, exactly like this:

// Rotation methods for iOS 6
- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

4 - I would advice to also include the method for autorotation for iOS 5 inside the class you want in landscape:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!