一.前言: 现在有很多程序大多是仅支持某个方向,但是不排除在某些界面需要强制支持某个方向,这里以(竖屏下强制支持横屏)为例;
二.代码实现:
1.在程序中需要我们的程序支持全部的方向,在General中设置,如下图
2.在APPDelegate.h文件中增加一属性,用于控制方向的切换;
@property(nonatomic,assign)BOOL allowRotation;//是否允许转向
3在AppDelegate.m文件中添加方法(如果属性值为YES,仅允许屏幕向左旋转,否则仅允许竖屏)
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
if (_allowRotation == YES) {
return UIInterfaceOrientationMaskLandscapeLeft;
}else{
return (UIInterfaceOrientationMaskPortrait);
}
}
4.在我们需要强制横屏的控制器中添加实现方法;
//UIButton控制开关
-(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];
}