A-A+

iOS在某个页面强制横屏

博客主机

最近在网上找了很多关于如何在某一个页面强制横屏的资料,但是还是没有实现预期的效果。最后经过不懈努力,最终还是找到了一个可以实现这一需求的方法。下面就将该方法整理出来,并附带demo下载。供以后在开发中方便使用。

方法实现部分

在AppDelegate.h中定义一个属性,如下:

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

AppDelegate.m中实现横屏或竖屏的设置:

///// 如果属性值为YES,仅允许屏幕向左旋转,否则仅允许竖屏。
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {

    if (self.allowRotation == YES) {

        // 横屏
        return UIInterfaceOrientationMaskLandscape;
    } else {

        // 竖屏
        return (UIInterfaceOrientationMaskPortrait);
    }
}

在UIDevice分类中实现强制转屏,如下:

/// 输入要强制转屏的方向
/// @param interfaceOrientation 转屏的方向
+ (void)deviceMandatoryLandscapeWithNewOrientation:(UIInterfaceOrientation)interfaceOrientation {

    NSNumber *resetOrientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationUnknown];

    [[UIDevice currentDevice] setValue:resetOrientationTarget forKey:@"orientation"];

    // 将输入的转屏方向(枚举)转换成Int类型
    int orientation = (int)interfaceOrientation;

    // 对象包装
    NSNumber *orientationTarget = [NSNumber numberWithInt:orientation];

    // 实现横竖屏旋转
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}

应用部分

关于应用部分的代码,在需要旋转屏幕的地方调用如下方法:

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    // 打开横屏开关
    appDelegate.allowRotation = YES;
    // 调用转屏代码
    [UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationLandscapeRight];

在返回到上一个页面的时候,如果需要保持原来的竖屏,那么就应该实现对应的方法即可:

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    // 关闭横屏仅允许竖屏
    appDelegate.allowRotation = NO;
    // 切换到竖屏
    [UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationPortrait];

    

好了,代码的主要实现部分都已经完成了,高高兴兴的进入调试阶段,结果怎么也不能实现预期效果。这又是什么原因呢,难道是代码层面还有什么问题没处理好?仔细检查了一下,原来是下面的原因:没错,你只要需要将Requires full screen这个选项钩上就大功告成了。

标签:

给我留言

Copyright © ios教程,苹果粉丝,苹果资讯,ios入门教程,ios学习,ios程序员,ios视频教程,ios粉丝网 保留所有权利.   Theme  Ality

用户登录