很多时候有强制横屏的需求. 首先要明确一个东西
项目里面必须要勾选可以旋转的方向, 如果不勾选, 代码无效!
直接上代码,按照我的步骤来,包你实现功能
第一:
#import "AppDelegate.h"
在AppDelegate 添加下面的属性以及方法.
/**
* 是否允许转向
*/
@property(nonatomic,assign)BOOL allowRotation;
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
if (self.allowRotation == YES) {
//横屏
return UIInterfaceOrientationMaskLandscape;
}else{
//竖屏
return UIInterfaceOrientationMaskPortrait;
}
}
第二: 添加分类
.h 文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIDevice (TFDevice)
/**
* @interfaceOrientation 输入要强制转屏的方向
*/
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end
NS_ASSUME_NONNULL_END
.m 文件
#import "UIDevice+TFDevice.h"
@implementation UIDevice (TFDevice)
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation
{
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:interfaceOrientation];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
@end
第三:到需要旋转的控制器
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.navigationController.navigationBar setHidden:YES];
//禁用侧滑手势方法
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.navigationController.navigationBar setHidden:NO];
//开启侧滑手势方法
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
- (void)viewDidLoad {
[super viewDidLoad];
//设置横屏
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//允许转成横屏
appDelegate.allowRotation = YES;
//调用横屏代码
[UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
}
//如果 push 和 pop 之后需要强制竖屏
//push和 pop 代码前加上下面的代码
//点击导航栏返回按钮的时候调用,所以Push出的控制器最好禁用侧滑手势:
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
//切换到竖屏
[UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
push,pop...代码