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

来源:互联网 发布:淘宝上的国内专柜代购 编辑:程序博客网 时间:2024/06/04 19:33

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

二.代码实现:

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


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

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


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

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullableUIWindow *)window

{

    if (_allowRotation ==YES) {

        returnUIInterfaceOrientationMaskLandscapeLeft;

    }else{

        return (UIInterfaceOrientationMaskPortrait);

    }

}

4.在我们需要强制横屏的控制器中添加实现方法;

//UIButton控制开关

-(void)fullBtnClick:(NLCustomButton *)sender

{

    AppDelegate * appDelegate = (AppDelegate *)[UIApplicationsharedApplication].delegate;

    if (sender.selected ==NO) {//打开横屏

        appDelegate.allowRotation =YES;

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

    }

    else

    {

        appDelegate.allowRotation =NO;//关闭横屏

        [selfsetNewOrientation:NO];//调用转屏代码

    }

    sender.selected = !sender.selected;

}

//转屏核心代码

- (void)setNewOrientation:(BOOL)fullscreen

{

    if (fullscreen) {

        NSNumber *resetOrientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationUnknown];

        [[UIDevicecurrentDevice] setValue:resetOrientationTargetforKey:@"orientation"];

        NSNumber *orientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationLandscapeLeft];

        [[UIDevicecurrentDevice] setValue:orientationTargetforKey:@"orientation"];

    }else{

        NSNumber *resetOrientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationUnknown];

        [[UIDevicecurrentDevice] setValue:resetOrientationTargetforKey:@"orientation"];

        NSNumber *orientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationPortrait];

        [[UIDevicecurrentDevice] setValue:orientationTargetforKey:@"orientation"];

    }

}

//离开这个界面别忘记关闭横屏

-(void)pushOrback

{

    AppDelegate * appDelegate = (AppDelegate *)[UIApplicationsharedApplication].delegate;

    appDelegate.allowRotation =NO;

    [selfsetNewOrientation:NO];

}









原创粉丝点击