iOS开发---强制某个界面横屏

前言

现在有很多程序大多是仅支持某个方向,但是不排除在某些界面需要强制支持某个方向,这里以(竖屏下强制支持横屏)为例;

代码实现

1.在General中设置程序支持全部的方向,如下图

2.在AppDelegate.h文件中增加allowRotation属性,用于控制方向的切换

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

3.在AppDelegate.m文件中实现方法

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
    if (_allowRotation == YES) { //仅允许屏幕向左旋转
        return UIInterfaceOrientationMaskLandscapeLeft;
    }else{ //仅允许竖屏
        return (UIInterfaceOrientationMaskPortrait);
    }
}

4.在需要强制横屏的界面中调用

//全屏按钮
-(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];
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值