第一步
在AppDelegate中添加方法关闭横竖屏切换,方法如下
AppDelegate.h中外露一个属性
@property( nonatomic , assign ) BOOL allowRotation;//标识是否允许转向
AppDelegate.m中增加如下方法
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
if (_allowRotation == YES) { // 如果属性值为YES,仅允许屏幕向左旋转,否则仅允许竖屏
return UIInterfaceOrientationMaskLandscapeRight; // 此处是屏幕要旋转的方向
}else{
return (UIInterfaceOrientationMaskPortrait);
}
}
第二步
在需要强制横屏的页面写上如下代码:
- 在viewDidLoad 方法设置如下:
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = YES;//(打开AppDelegate里的横屏开关)
[self setNewOrientation:YES];//调用转屏代码
- 实现setNewOrientation方法:
- (void)setNewOrientation:(BOOL)fullscreen{
if (fullscreen) {
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}else{
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}
}
注意点
有些导航控制器push出来的页面,如果在导航控制器里写了侧滑代理及手势,可能会导致部分强制横屏页面没法横屏,此时需要把导航控制器里侧滑手势代码屏蔽删除即可。
- (void)viewDidLoad {
[super viewDidLoad];
//就这句话导致了push出来的页面无法强制横屏
//self.interactivePopGestureRecognizer.delegate = self;
self.navigationBar.barTintColor = [UIColor whiteColor];//64B4FA//64C83C//7F9CFF
[self.navigationBar setTitleTextAttributes:@{NSFontAttributeName:T18Font_M, NSForegroundColorAttributeName:C16}];
}