首先选择支持的旋转方向(两种方法,推荐第二种)
(1)修改Info.plist文件,见图1
(2)直接上图,(勾选即可)
2.在AppDelegate中添加属性方法
在.h中添加一个属性allowRotation
@interfaceAppDelegate: UIResponder@property(strong, nonatomic) UIWindow *window;@property(nonatomic,assign)BOOL allowRotation;//是否允许转向@end
.m中添加下面的方法
- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(nullableUIWindow*)window{if(_allowRotation ==YES) {returnUIInterfaceOrientationMaskLandscapeRight; }else{return(UIInterfaceOrientationMaskPortrait); }}
3.在你需要旋转的控制器.m中添加一下方法
- (void)setNewOrientation:(BOOL)fullscreen{if(fullscreen) {NSNumber*resetOrientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationUnknown]; [[UIDevicecurrentDevice] setValue:resetOrientationTarget forKey:@"orientation"];NSNumber*orientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationLandscapeRight]; [[UIDevicecurrentDevice] setValue:orientationTarget forKey:@"orientation"]; }else{NSNumber*resetOrientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationUnknown]; [[UIDevicecurrentDevice] setValue:resetOrientationTarget forKey:@"orientation"];NSNumber*orientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationPortrait]; [[UIDevicecurrentDevice] setValue:orientationTarget forKey:@"orientation"]; }}
4.点击旋转按钮调用- (void)setNewOrientation:(BOOL)fullscreen方法
//横竖屏切换按钮方法-(void)screen{//记着#import "AppDelegate.h"AppDelegate * appDelegate = (AppDelegate *)[UIApplicationsharedApplication].delegate;if(_fullScreen ) {//横屏情况下,点击此按钮变为竖屏appDelegate.allowRotation =NO;//设置竖屏[selfsetNewOrientation:NO];//调用转屏代码self.navigationController.navigationBar.hidden =NO;//navbar消失[selfsetViewFrame:NO];//竖屏布局}else{//竖屏情况下,点击此按钮变为横屏appDelegate.allowRotation =YES;////设置横屏[selfsetNewOrientation:YES];////调用转屏代码self.navigationController.navigationBar.hidden =YES;//navbar出现[selfsetViewFrame:YES];//横屏布局}}
3.获取当前屏幕是竖屏还是横屏
#import"AppDelegate.h"
@interfaceJGCameraViewController()
@property(nonatomic,assign)UIInterfaceOrientationinterfaceOrientation;
@end
- (void)viewWillAppear:(BOOL)animated {
[superviewWillAppear:animated];//改变AppDelegate的appdelegete.allowRotation属性AppDelegate*appdelegete = (AppDelegate*)[UIApplicationsharedApplication].delegate;appdelegete.allowRotation=YES;self.interfaceOrientation=1;
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
self.interfaceOrientation= interfaceOrientation;switch(interfaceOrientation) {caseUIInterfaceOrientationPortrait://home健在下break;
caseUIInterfaceOrientationPortraitUpsideDown:
//home健在上
break;
caseUIInterfaceOrientationLandscapeLeft:
//home健在左
break;
caseUIInterfaceOrientationLandscapeRight://home健在右
break;
default:
break;
}
}