- 首先选择支持的旋转方向(两种方法,推荐第二种)
(1)修改Info.plist文件,见图1
(2)直接上图,(勾选即可)
2.在AppDelegate中添加属性方法
在.h中添加一个属性allowRotation@interface AppDelegate : UIResponder @property (strong, nonatomic) UIWindow *window; @property(nonatomic,assign)BOOL allowRotation;//是否允许转向 @end
.m中添加下面的方法
- (UIInterfaceOrientationMa
sk)application:(UIApplication *)application supportedInterfaceOrient ationsForWindow:(nullable UIWindow *)window{ if (_allowRotation == YES) { return UIInterfaceOrientationMa skLandscapeRight; }else{ return (UIInterfaceOrientationMa skPortrait); } } 3.在你需要旋转的控制器.m中添加一下方法
- (void)setNewOrientation:(BOOL)fullscreen{ if (fullscreen) { NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUn
known]; [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"]; NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLa ndscapeRight]; [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"]; }else{ NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUn known]; [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"]; NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPo rtrait]; [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"]; } } 4.点击旋转按钮调用- (void)setNewOrientation:(BOOL)fullscreen方法
//横竖屏切换按钮方法 -(void)screen{ //记着#import "AppDelegate.h" AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; if (_fullScreen ) {//横屏情况下,点击此按钮变为竖屏 appDelegate.allowRotation = NO;//设置竖屏 [self setNewOrientation:NO];//调用转屏代码 self.navigationController.navigationBar.hidden = NO;//navbar消失 [self setViewFrame:NO];//竖屏布局 }else{//竖屏情况下,点击此按钮变为横屏 appDelegate.allowRotation = YES;设置横屏 [self setNewOrientation:YES];调用转屏代码 self.navigationController.navigationBar.hidden = YES;//navbar出现 [self setViewFrame:YES];//横屏布局 } }
3.获取当前屏幕是竖屏还是横屏
#import "AppDelegate.h"
@interface JGCameraViewController ()
@property (nonatomic, assign) UIInterfaceOrientation interfaceOrientation;
@end
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated]; //改变AppDelegate的appdelegete.allowRotation属性 AppDelegate *appdelegete = (AppDelegate *)[UIApplication sharedApplication].delegate; appdelegete.allowRotation = YES; self.interfaceOrientation = 1;
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
self.interfaceOrientation = interfaceOrientation; switch (interfaceOrientation) { case UIInterfaceOrientationPo rtrait: //home健在下 break;
case UIInterfaceOrientationPo rtraitUpsideDown:
//home健在上
break;
case UIInterfaceOrientationLa ndscapeLeft:
//home健在左
break;
case UIInterfaceOrientationLa ndscapeRight: //home健在右
break;
default:
break;
}
}