iOS 强制旋转屏幕

前言

在开发中有时会碰到旋转屏幕的需求,例如直播时横竖屏推流,这里我使用的一种方法时用纯代码强制翻转,其他晚上方法也都使用过,但是效果并不好,目前这个方法还可以。

步骤

  • 1.AppDelegate中配置
//AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
//允许横屏
@property (nonatomic, assign) BOOL allowLandscapeRight;
@end

//AppDelegate.m 增加此方法
//横竖屏切换使用
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if (self.allowLandscapeRight) {
        return UIInterfaceOrientationMaskLandscapeRight;
    }
    return UIInterfaceOrientationMaskPortrait;
}

  • 2.在要跳转的界面
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowLandscapeRight = YES;
    //强制旋转成全屏
    NSNumber *value = [NSNumber numberWithInt:UIDeviceOrientationLandscapeLeft];
    [[UIDevice currentDevice]setValue:value forKey:@"orientation"];
    [UIViewController attemptRotationToDeviceOrientation];

    [self.navigationController pushViewController:[[YouVC alloc] init] animated:YES];
  • 3.在退出的时候
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowLandscapeRight = NO;
   //强制旋转成竖屏
    NSNumber *value = [NSNumber numberWithInt:UIDeviceOrientationPortrait];
   [[UIDevice currentDevice]setValue:value forKey:@"orientation"];
   [UIViewController attemptRotationToDeviceOrientation];
}

问题

可能会碰到状态栏不显示的问题,详见我的上一篇文章 iOS 状态栏更改颜色、适配等

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

推荐阅读更多精彩内容

  • 项目需求: 我只是以第一个需求为例,第二种情况,道理相同。 无需强行选中 Device Orientation 中...
    木木等你阅读 2,221评论 0 2
  • // 状态栏动画持续时间CGFloat duration = [UIApplication sharedAppli...
    在这蓝色天空下阅读 726评论 0 3
  • 最近接手了一个项目,正常情况下使用查看图片是没问题的。 用到了 MWPhotoBrowser 这个第三方图片浏览库...
    WhoJun阅读 5,729评论 5 51
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,666评论 25 708
  • 玩,是儿童的天性。 玩,从呀呀学语起。 玩,从学会走路上。 玩,从会叫爸妈会问我从哪里来的时候起。 玩,不需要思考...
    画心心语阅读 585评论 0 2