iOS16适配:APP切换横竖屏问题

iOS16之前切换横竖屏使用的是UIDevicesetValue:forKey:方法进行切换。但在iOS16后不再支持使用setValue方法设置设备的方向,建议替换为UIWindowScenerequestGeometryUpdate方法。

iOS16之前切换屏幕方法:

///竖屏
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
///横屏
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];

iOS16之后切换屏幕方法:

///竖屏
if (@available(iOS 16.0, *)) {
    [self.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
    NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
    UIWindowScene *ws = (UIWindowScene *)array[0];
    UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
    geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskPortrait;
    [ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
         //业务代码
    }];
} else {
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
}
//横屏
if (@available(iOS 16.0, *)) {
    [self.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
    NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
    UIWindowScene *ws = (UIWindowScene *)array[0];
    UIWindowSceneGeometryPreferencesIOS *geometryPreferences =     [[UIWindowSceneGeometryPreferencesIOS alloc] init];
    geometryPreferences.interfaceOrientations =     UIInterfaceOrientationMaskLandscapeLeft;
    [ws requestGeometryUpdateWithPreferences:geometryPreferences     errorHandler:^(NSError * _Nonnull error) {
         //业务代码
    }];
} else {
    [[UIDevice currentDevice] setValue:[NSNumber   numberWithInteger:UIDeviceOrientationUnknown] forKey:@"orientation"];
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
}

注意:[self.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];这段代码,需要写在在转屏的页面合适位置,否则转屏不起作用,导致监听转屏的方法viewWillTransitionToSize: viewWillTransitionToSize未被回调(自动转屏时也不会回调)。

你可能感兴趣的:(iOS16适配:APP切换横竖屏问题)