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,210評論 0 2
  • // 狀態欄動畫持續時間CGFloat duration = [UIApplication sharedAppli...
    在這藍色天空下閱讀 725評論 0 3
  • 最近接手了一個項目,正常情況下使用查看圖片是沒問題的。 用到了 MWPhotoBrowser 這個第三方圖片瀏覽庫...
    WhoJun閱讀 5,723評論 5 51
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,284評論 25 708
  • 玩,是兒童的天性。 玩,從呀呀學語起。 玩,從學會走路上。 玩,從會叫爸媽會問我從哪里來的時候起。 玩,不需要思考...
    畫心心語閱讀 577評論 0 2