iOS 16橫屏適配

項目中寫好了橫屏適配,一直也忘了整理出來,今天正好周五有空記錄一下
先在AppDelegate文件中添加

//AppDelegate.h
@property (nonatomic, assign) BOOL screenOrientations;    /**< 是否是橫屏 */
- (void)setScreenOrientations:(BOOL)screenOrientations;

//AppDelegate.m
- (void)setScreenOrientations:(BOOL)screenOrientations {
    _screenOrientations = screenOrientations;
    [self application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:nil];
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.screenOrientations) {
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
}

去要橫屏的頁面加入下面代碼

//viewWillDisappear方法添加
[self.appDelegate setscreenOrientations:NO];

//viewDidLoad方法添加
  if (@available(iOS 16.0, *)) {
        [self.appDelegate setscreenOrientations:YES];
  }

/// 切換設備方向
- (void)p_switchOrientationWithLaunchScreen{
    if (@available(iOS 16.0, *)) {
        // setNeedsUpdateOfSupportedInterfaceOrientations 方法是 UIViewController 的方法,所以這個操作最好是放在控制器中去操作
        [self setNeedsUpdateOfSupportedInterfaceOrientations];
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        // 屏幕方向
        UIInterfaceOrientationMask orientation = UIInterfaceOrientationMaskLandscapeRight;
        UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation];
        // 開始切換
        [scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS errorHandler:^(NSError * _Nonnull error) {
        }];
    } else {
        [self swichOldOrientation:UIInterfaceOrientationLandscapeRight];
    }
}
/// iOS16 之前進行橫豎屏切換方式
- (void)swichOldOrientation:(UIInterfaceOrientation)interfaceOrientation {
    NSNumber *orientationTarget = [NSNumber numberWithInteger:interfaceOrientation];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
}

在我的swift項目中貌似沒啥影響,如果下面代碼不行,可以自行將上面的oc代碼轉成swift

  /// 屏幕方向
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscapeRight
    }
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 項目中有個頁面需要強制橫屏,代碼邏輯實現(xiàn)如下。首先,創(chuàng)建一個UINavigationController的子類Cu...
    z_hy閱讀 1,016評論 2 1
  • 項目中針對某一個 View 需要進行橫屏,在 iOS16 之前的方式大部分都是采取設置設備的方向來實現(xiàn)的,但是在 ...
    CoderGuogt閱讀 23,819評論 27 59
  • 目錄 一、最讓人糾結的三種枚舉 二、兩種屏幕旋轉的觸發(fā)方式 三、屏幕旋轉控制的優(yōu)先級 四、開啟屏幕旋轉的全局權限 ...
    來鬧的閱讀 3,098評論 0 4
  • 目錄一、最讓人糾結的三種枚舉二、兩種屏幕旋轉的觸發(fā)方式三、屏幕旋轉控制的優(yōu)先級四、開啟屏幕旋轉的全局權限五、開啟屏...
    Faner_NG閱讀 5,019評論 2 18
  • 第一步 首先保證工程支持橫豎屏 不多說看圖 保證圈紅的地方 打對勾 58F678EC-EABC-4320-9FCB...
    ylgwhyh閱讀 2,012評論 0 1

友情鏈接更多精彩內容