iOS16适配记录

5,085 阅读1分钟

1.屏幕旋转问题

在iOS16的真机运行项目时,在需要转屏的页面收到了警告

[Orientation] BUG IN CLIENT OF UIKIT: Setting UIDevice.orientation is not supported. Please use UIWindowScene.requestGeometryUpdate(_:)

通过描述可以发现UIDevice.orientation这个形式已经不再被支持,。在iOS16里这个方法被禁用了
兼容处理如下:

if ( @availableiOS 16.0, *)) {

        AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

        delegate.allowRotate = 1;

        

        if ([[UIViewController currentViewController] respondsToSelector: @selector(setNeedsUpdateOfSupportedInterfaceOrientations)]) {

            [[UIViewController currentViewController] performSelector: @selector(setNeedsUpdateOfSupportedInterfaceOrientations)];

        }
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];

        UIWindowScene *ws = (UIWindowScene *)array[0];

        Class GeometryPreferences = NSClassFromString(@"UIWindowSceneGeometryPreferencesIOS");

        id geometryPreferences = [[GeometryPreferences alloc] init];

        [geometryPreferences setValue:@(UIInterfaceOrientationMaskLandscapeRight) forKey:@"interfaceOrientations"];

        if ([ws respondsToSelector: @selector(requestGeometryUpdateWithPreferences:errorHandler:)]) {

            [ws performSelector: @selector(requestGeometryUpdateWithPreferences: errorHandler:) withObject:geometryPreferences withObject:nil];

            AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            delegate.allowRotate = 2;

        }

    }else{
//旧的转屏逻辑 setOrientation的时候会触发appdelegate里面的supportedInterfaceOrientationsForWindow方法,此方法会根据当前的方向参数转屏
        AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

        delegate.allowRotate = 1;

        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 = UIInterfaceOrientationLandscapeRight; //横屏

            [invocation setArgument:&val atIndex:2];

            [invocation invoke];

            delegate.allowRotate = 2;

        }

    }