iOS强制横屏

由于项目需求,需要整个项目页面都是竖屏,唯独一个折线图页面强制性横屏显示. 网上逛了许多帖子,也看了好多大神的提供的方法,都没能够实现我想要的效果.没办法自己研究自己搞,借鉴各路大神的思路,最后费劲千辛万苦,终于实现了想要的效果。

废话不多说,上干货

 

第一步:

Xcode工程配置中的Device Orientation有四个方向,勾选某个方向,即表示支持该方向的旋转(我这里除了倒置其余三个都选中了)

这一步完成,旋转手机或者模拟器,画面就会对应转换横竖屏(模拟器模拟转换方向按键为:command+上下左右)

 

第二步:

在AppDelegate中添加方法关闭横竖屏切换,方法如下

1.AppDelegate.h中外露一个属性

@property(nonatomic,assign)BOOL allowRotation;//是否允许转向

 

2.AppDelegate.m中添加方法(如果属性值为YES,仅允许屏幕向左旋转,否则仅允许竖屏)

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

{

    if (_allowRotation == YES) {

        return UIInterfaceOrientationMaskLandscapeLeft;

    }else{

        return (UIInterfaceOrientationMaskPortrait);

    }

}

 

第三步:

1.在需要强制横屏的控制器.m中添加旋转为横屏方法

- (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"];

    }

}

 

2.view DidLoad中添加以下代码

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

    appDelegate.allowRotation = YES;//(以上2行代码,可以理解为打开横屏开关)

[self setNewOrientation:YES];//调用转屏代码

 

3.重写导航栏返回箭头按钮,拿到返回按钮点击事件

- (void)back

{

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

    appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏

    [self setNewOrientation:NO];

    [self.navigationController popViewControllerAnimated:YES];

}

大功告成,强制横屏功能实现,而且重力感应不会转屏。

转载于:https://www.cnblogs.com/block123/p/5917770.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值