1、如果是全局设置
1)、在工程targets直接勾选device orientation
2)、在项目的根视图控制器中
-(BOOL)shouldAutorotate{
returnYES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
returnUIInterfaceOrientationMaskAll;
}
-(BOOL)shouldAutorotate{
//这里修改为根据navigationController或者tabarController的shouldAutoRotate属性设置返回值
//returnYES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
returnUIInterfaceOrientationMaskAll;
}
在需要实现旋转的界面中重写-(BOOL)shouldAutorotate{
return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
returnUIInterfaceOrientationMaskPortrait;
}
原理应该是:只有根视图中实现的两个方法起决定性作用,虽然子界面中的两个方法也会调用,但他只会通过改变 navigationController、tabarController的shoulAutoRotate属性值将返回值传给根视图控制器中的方法,由根视图控制器完成操作// 每次试图切换的时候都会走的方法,用于控制设备的旋转方向.
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (_isRotate) {
returnUIInterfaceOrientationMaskAll;
}else {
returnUIInterfaceOrientationMaskPortrait;
}
}
然后在需要支持旋转的界面中添加一个单例模式的属性_myAppDelegate,
-(void)viewWillAppear:(BOOL)animated{
_myAppDelegate=[[UIApplicationsharedApplication]delegate];
_myAppDelegate.isRotation=YES;
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
_myAppDelegate.isRotation=NO;
}
每次发生方向变化就会Appdelegate中的方法会被调用,此时会根据单例的appDelegate的属性_isRotate判断是否发生改变
3、对设备横竖屏问题的修正和补充
1)不管是整个应用支持多方向还是部分界面支持多方向,首先需要让整个应用支持多方向,最好的方法是在info.plist中Supported interface orientations中只支持portraint,然后在appDelegate中用代码实现(我自己遇到在info.plist中支持多方向,应用加载页面会根据设备方向显示方向)
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
returnUIInterfaceOrientationMaskAll;
}
然后在每个根视图控制器中实现方法
-(BOOL)shouldAutorotate{
return YES;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
returnUIInterfaceOrientationMaskPortrait;
}
我们一般用tabbarController和navigationController作为根视图控制器管理子控制器的旋转方向,例如一个tabbarController
@interface UITabBarController (RotateTabBarController)
@end
#import "UITabBarController+RotateTabBarController.h"
@implementation UITabBarController (RotateTabBarController)
a)-(BOOL)shouldAutorotate
{
}
b)-(NSUInteger)supportedInterfaceOrient
{
}
如果是navigationController,由它推出的所有子控制器跟navigationController中设置是一样的(或者也可以像tabbarController那样根据index控制?没试),在子控制器中重写上面两个方法是无效的。
c)/-(UIInterfaceOrientation)preferredInterfaceOrient
//{
//
//
//
//
//
//
//
//
//}
2)每次通过presentViewController模态推出视图控制器的时候,就得重写上面a、b两个方法,这种时候如果推出的视图较多,就可以选择再建立一个navigationController作为根视图控制器像上面那样管理,为了简化工作,我们可以通过重写navigationController的子类在其中新添加上面两个方法或者通过navigationcontroller的category方式新增两个方法,之后每次使用这个navigationController的子类作为根视图控制器。Note:上面a、b两个方法调用顺序是先检查supportedInterfaceOrient
preferredInterfaceOrientationForPresentation
此方法也属于UIViewController
. 影响当前viewController
的初始显示方向. 此方法也仅有在当前viewController
是rootViewController
或者是modal
模式时才生效.