前言
现在有很多程序大多是仅支持某个方向,但是不排除在某些界面需要强制支持某个方向,这里以(竖屏下强制支持横屏)为例;
代码实现
1.在General中设置程序支持全部的方向,如下图
2.在AppDelegate.h文件中增加allowRotation属性,用于控制方向的切换
@property(nonatomic,assign)BOOL allowRotation;//是否允许转向
3.在AppDelegate.m文件中实现方法
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
if (_allowRotation == YES) { //仅允许屏幕向左旋转
return UIInterfaceOrientationMaskLandscapeLeft;
}else{ //仅允许竖屏
return (UIInterfaceOrientationMaskPortrait);
}
}
4.在需要强制横屏的界面中调用
//全屏按钮
-(void)fullBtnClick:(NLCustomButton *)sender{
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
if (sender.selected == NO) {//打开横屏
appDelegate.allowRotation = YES;
[self setNewOrientation:YES];//调用转屏代码
}
else {
appDelegate.allowRotation = NO;//关闭横屏
[self setNewOrientation:NO];//调用转屏代码
}
sender.selected = !sender.selected;
}
//设定设备屏幕方向
- (void)setNewOrientation:(BOOL)fullscreen{
if (fullscreen) {
NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];
[[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];
NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[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"];
}
}
//关闭横屏
-(void)pushOrback{
AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowRotation = NO;
[self setNewOrientation:NO];
}