iOS [Orientation] BUG IN CLIENT

2023-06-17  本文已影响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];
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读