代码示例
-
Appdelegate添加属性(在Appdelegate.m中添加该属性)
/** 是否允许横屏属性*/ @property (nonatomic,assign)BOOL isAllowRotation;
-
设置可以支持的方向(在AppDelegate.m中添加)
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{ if (self.isAllowRotation) { return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight; } return UIInterfaceOrientationMaskPortrait; }
-
设置控制横竖屏打开关闭的方法(在AppDelegate.m中添加)
/** 允许横屏*/ - (void)setCanAllowRotation{ self.isAllowRotation =YES; } /** 禁止横屏*/ - (void)setCanNotAllowRotation{ self.isAllowRotation =NO; }
-
在AppDelegate.h中声明两个方法
/** 支持横屏接口,需要在view消失时设置为不支持,否则其他页面也会支持横屏*/ - (void)setCanAllowRotation; /** 不支持横屏接口*/ - (void)setCanNotAllowRotation;
-
在pch文件中添加这部分代码
/** 获得appdelegate*/ #define APPDELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate] //不支持横屏 #define CANNOTSCALE AppDelegate * appDelegate = APPDELEGATE;[appDelegate setCanNotAllowRotation]; //支持横屏 #define CANSCALE AppDelegate * appDelegate = APPDELEGATE;[appDelegate setCanAllowRotation];
代码说明
-
需要在需要使用的viewController中的viewWillAppear中打开支持横竖屏,然后在viewWillDisAppear中关闭支持横竖屏,下面是调用展示
- (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; CANSCALE } - (void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; CANNOTSCALE }