美文网首页
iOS [Orientation] BUG IN CLIENT

iOS [Orientation] BUG IN CLIENT

作者: 笔头还没烂 | 来源:发表于2023-06-17 12:13 被阅读0次

原代码是这样:

      - (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];
        }
    }
}

相关文章

网友评论

      本文标题:iOS [Orientation] BUG IN CLIENT

      本文链接:https://www.haomeiwen.com/subject/vhbdydtx.html