iOS开发之强制横竖屏

步骤和代码

  • 第一步 :Appdelegate文件中设置

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

//在AppDelegate.h文件中设置两个属性
@property(nonatomic, assign) BOOL isForcePortrait;
@property(nonatomic, assign) BOOL isForceLandscape;

@end

//在AppDelegate.m文件中实现代理方法
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    if (self.isForceLandscape) {
        return UIInterfaceOrientationMaskLandscape;
    }else if (self.isForcePortrait){
        return UIInterfaceOrientationMaskPortrait;
    }else{
        return UIInterfaceOrientationMaskAll;
    }
}
  • 第二步:设置横竖屏的方法,写在分类中
//UIDevice+TFDevice.h文件
#import <UIKit/UIKit.h>

@interface UIDevice (TFDevice)
//interfaceOrientation 输入要强制转屏的方向
+ (void)switchNewOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end

//UIDevice+TFDevice.m文件
#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

  • 第三步:设置横竖屏
#pragma  mark - 强制横竖屏设置
- (void)forceOrientationLandscape { //强制横屏
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.isForcePortrait = NO;
    appDelegate.isForceLandscape = YES;
    [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
}
- (void)forceOrientationPortrait  { //强制竖屏
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.isForcePortrait = YES;
    appDelegate.isForceLandscape = NO;
    [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
}

注意

  • 这个在展示控制器的时候需要调用,在dismiss或者pop掉控制器的时候也需要将设置恢复原样。

  • 在第三步上强制横屏的以下这句代码中,后面的旋转方向仅仅是告诉屏幕要往横屏右方向转,至于转完之后屏幕能不能也能横屏左那就要看Appdelegate里面实现的代理方法怎么实现的了...

 [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];

DEMO传送门

参考

iOS强制横屏或强制竖屏

以上!!!

弹钢琴.gif
转自:https://www.jianshu.com/p/32ac0b200931
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

游鱼_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值