iOS强制横竖屏转换

https://www.jianshu.com/p/d6cb54d2eaa1  这篇文章给出的方案是可行的。

经测试,想要第一个界面强制横屏,第二个界面强制竖屏, dismiss掉之后回到第一个界面依然强制横屏。用户的手机设备禁止旋转按钮不打开状态下,旋转手机屏幕能依然强制横屏或者竖屏。

第一个界面强制横屏 在工程设置里

如果是要第一个界面强制竖屏 那么设置为

AppDelegate里的系统方法为:

AppDelegate.h里公开一个字段来确定是横屏还是竖屏   

@property(nonatomic,assign)BOOL allowRotation;

 

 

AppDelegate.m文件中添加代码

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window

 

{

    

    if (self.allowRotation == YES) {

        //横屏

        return UIInterfaceOrientationMaskLandscape;

        

    }else{

        //竖屏

        return UIInterfaceOrientationMaskPortrait;

        

    }

    

}

在第一个界面的控制器里添加代码

#import "AppDelegate.h"

#import "UIDevice+TFDevice.h"

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

     NSLog(@"%s",__func__);

    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    //允许转成横屏

    

    appDelegate.allowRotation = YES;

    //调用横屏代码

    

[UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeLeft];

    

}

 

在第二个界面的控制器里

添加代码

 

#import "AppDelegate.h"

#import "UIDevice+TFDevice.h"

 

- (void)viewDidLoad {

    [super viewDidLoad];

    NSLog(@"%s",__func__);

    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    //允许转成竖屏

   

    appDelegate.allowRotation = NO;

    //调用竖屏代码

 [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];

  

}

 

另外对UIDevice设备做一个分类扩展

@interface UIDevice (TFDevice)

/**

 * @interfaceOrientation 输入要强制转屏的方向

 */

+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;

@end

 

#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

原文地址:https://www.cnblogs.com/shycie/p/9120984.html