iOS [Orientation] BUG IN CLIENT OF UIKIT: Setting UIDevice.orientation is not supported. Please u...

原代码是这样:

      - (void)setInterfaceOrientation:(UIInterfaceOrientation)orientation {
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
            SEL selector = NSSelectorFromString(@"setOrientation:");
            NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:[UIDevice currentDevice]];
            int val = orientation;
            [invocation setArgument:&val atIndex:2];
            [invocation invoke];
        }

当需要强制旋转屏幕时,传入目标的 orientation 达到强制旋转屏幕的目的。但是,如题所示,在 iOS 16 中,通过设置设置 UIDevice.orientation 来强制旋转屏幕的方向已不再被支持。
根据错误提示,需要使用 UIWindowScene.requestGeometryUpdate(_:) 方法来实现。于是修改后的代码如下:

///强制转换屏幕方向
- (void)ll_interfaceOrientation:(UIInterfaceOrientation)orientation {
    
    if(@available(iOS 16.0, *)) {
        UIScene *windowScene = [[[UIApplication sharedApplication] connectedScenes] anyObject];
        UIWindowSceneGeometryPreferencesIOS *preferences = nil;
        if (orientation == UIInterfaceOrientationLandscapeRight || (orientation == UIInterfaceOrientationLandscapeLeft)) {
            preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskLandscape];
        }else {
            preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskPortrait];
        }
        [(UIWindowScene *)windowScene requestGeometryUpdateWithPreferences:preferences errorHandler:^(NSError * _Nonnull error) {
        }];

    }else {
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
    
            SEL selector = NSSelectorFromString(@"setOrientation:");
            NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:[UIDevice currentDevice]];
            int val = orientation;
            [invocation setArgument:&val atIndex:2];
            [invocation invoke];
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 声明:本文适配以iOS 16 bate 2为基准 背景 iOS 16在UIKIT上有了一些更改,废弃掉了一些修改方...
    不正常人类研究中心驴主任阅读 24,998评论 32 49
  • 目录 一、最让人纠结的三种枚举 二、两种屏幕旋转的触发方式 三、屏幕旋转控制的优先级 四、开启屏幕旋转的全局权限 ...
    来闹的阅读 3,100评论 0 4
  • iOS屏幕旋转学习笔记iOS开发中使用屏幕旋转功能的相关方法 1、基本知识点解读 了解屏幕旋转首先需要区分两种 o...
    Laughingg阅读 13,786评论 13 39
  • 1.强制应用为横屏的方法。在view contronller中的实现 (NSUInteger)supportedI...
    the宇亮阅读 476评论 0 0
  • 目录一、最让人纠结的三种枚举二、两种屏幕旋转的触发方式三、屏幕旋转控制的优先级四、开启屏幕旋转的全局权限五、开启屏...
    Faner_NG阅读 5,021评论 2 18

友情链接更多精彩内容