iOS屏幕旋转方向的相关方法

在iOS应用开发过程中,经常会遇到设置屏幕方向,或者根据屏幕方向改变界面的时候,所以现在就来说一下屏幕方向的那些事情。

关于方向,经常会遇到以下的两个对象:

1.UIDeviceOrientation(机器设备的方向)

==================================

    UIDeviceOrientationUnknown //未知方向

    UIDeviceOrientationPortrait, //设备直立,home按钮在下

    UIDeviceOrientationPortraitUpsideDown,  //设备直立,home按钮在上

    UIDeviceOrientationLandscapeLeft,       //设备横置,home按钮在右

    UIDeviceOrientationLandscapeRight,      //设备横置, home按钮在左

    UIDeviceOrientationFaceUp,              //设备平放,屏幕朝上

    UIDeviceOrientationFaceDown             //设备平放,屏幕朝下

==================================

2.UIInterfaceOrientation(界面的方向,iOS6之后可以去看UIInterfaceOrientationMask

==================================

    UIInterfaceOrientationPortrait //竖向,home按钮在下

    UIInterfaceOrientationPortraitUpsideDown //竖向,home按钮在上

    UIInterfaceOrientationLandscapeLeft //横向,home按钮在左

    UIInterfaceOrientationLandscapeRight //横向,home按钮在右

==================================

界面的开发主要使用UIInterfaceOrientation

一.获取当前界面方向

二.界面方向改变时,会调用的方法

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {}//视图旋转之前自动调用

-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {}//旋转方向发生改变时自动调用

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {}//视图旋转完成之后自动调用

三.设置界面支持的方向

1.全局设置

1.1工程设置(XCode5为例)

Targets->General->DeploymentInfo->Device Orientation进行设置

1.2在AppDelegate.m中设置(iOS6之后)

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{

    return UIInterfaceOrientationMaskPortrait;

}

2.一般情况下设置单个界面

iOS6之后:

-(BOOL)shouldAutorotate{

    return YES;

}//是否支持旋转

-(NSUInteger)supportedInterfaceOrientations{

    return UIInterfaceOrientationMaskLandscapeRight;

}//支持的方向

iOS6之前:

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{

    return toInterfaceOrientation == UIInterfaceOrientationLandscapeRight;

}


3.特例

引用了UINavigationController,需要改变的视图的是UINavigationController的RootViewController

那么需要新建一个UINavigationController的子类(当然要设置改变的视图是该子类的RootViewController),在这个子类里面添加下面的方法

- (BOOL)shouldAutorotate    
{    
    return self.topViewController.shouldAutorotate;    
}    
    
- (NSUInteger)supportedInterfaceOrientations    
{    
    return self.topViewController.supportedInterfaceOrientations;    
}  

然后在对每个视图分别按2进行设置

参考链接:

1.http://blog.csdn.net/zzfsuiye/article/details/8251060

2.http://www.cocoachina.com/applenews/devnews/2012/1218/5364.html

3.http://my.oschina.net/LouWk/blog/203084

原文地址:https://www.cnblogs.com/qisedao0215/p/3728811.html