1. 总开关在工程设置,General-Deployment Info-Device Orientation下勾选工程需要的选项。如果程序中所有的页面不会用到横屏,则只需要勾选Portrait。如果工程中部分页面需要横屏,则需要勾选竖屏和横屏的选项。
2. 在AppDelegate中设置旋转页面:
在AppDelegate.h文件中添加一个Flag,用来设置App全局是否可以横屏。
@property (nonatomic, assign) BOOL isPotrait; //设置整个App是否可以旋转
在AppDelegate.m文件中设置App的旋转代理方法。
#pragma mark-屏幕旋转相关的方法 - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{ if (self.isPotrait) { return UIInterfaceOrientationMaskPortrait; }else{ return UIInterfaceOrientationMaskAllButUpsideDown; } }
3. 单个的页面是否可以旋转,需要在代理方法中设置
#pragma mark-支持旋转的代理 - (BOOL)shouldAutorotate{ return YES; } - (UIInterfaceOrientationMask)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskAllButUpsideDown; }
4. ViewController嵌套在UINavigationController中,如果ViewController需要横屏展示,此时需要设置UINavigationController的选装代理方法。
这里提供一个自定义的UINavigationController的实现类:
CustomNavViewController.h
#import <UIKit/UIKit.h> @interface CustomNavViewController : UINavigationController @end
CustomNavViewController.m
#import "CustomNavViewController.h" @interface CustomNavViewController () @end @implementation CustomNavViewController - (void)viewDidLoad { [super viewDidLoad]; self.navigationBar.hidden = YES; // Do any additional setup after loading the view. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark-控制页面旋转的方法 - (BOOL)shouldAutorotate{ return self.topViewController.shouldAutorotate; } - (UIInterfaceOrientationMask)supportedInterfaceOrientations{ return self.topViewController.supportedInterfaceOrientations; } @end
5. ViewController嵌套在UITabBarController中,需要设置UITabBarController的旋转方向.
这里提供一个自定义的UITabBarController的类:
CustomTabBarController.h
#import <UIKit/UIKit.h> @interface CustomTabBarController : UITabBarController @end
CustomTabBarController.m
#import "CustomTabBarController.h" #import "CustomNavViewController.h" @interface CustomTabBarController () @end @implementation CustomTabBarController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark-控制旋转的代理方法 - (BOOL)shouldAutorotate{ CustomNavViewController *nav = (CustomNavViewController *)[self.viewControllers objectAtIndex:self.selectedIndex]; return nav.topViewController.shouldAutorotate; } - (UIInterfaceOrientationMask)supportedInterfaceOrientations{ CustomNavViewController *nav = (CustomNavViewController *)[self.viewControllers objectAtIndex:self.selectedIndex]; return nav.topViewController.supportedInterfaceOrientations; } @end