iOS在某个页面强制横屏

用代码实现在某页面强制横屏。
在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];

[self.navigationController popViewControllerAnimated:YES];
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容