ios 横竖屏切换(ios16适配)

直接上代码

     // 当前方向
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    // 是否是横屏
    BOOL isLandscape = (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight);
    if (@available(iOS 16.0, *)) {
        [self setNeedsUpdateOfSupportedInterfaceOrientations];
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        UIInterfaceOrientationMask orientation = isLandscape ?  UIInterfaceOrientationMaskPortrait : UIInterfaceOrientationMaskLandscapeRight;
        UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation];
        [scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS errorHandler:^(NSError * _Nonnull error) {
            NSLog(@"强制%@错误:%@", isLandscape ? @"横屏" : @"竖屏", error);
        }];
    } else {
        UIInterfaceOrientation orientationTarget  = isLandscape ? UIInterfaceOrientationPortrait : UIInterfaceOrientationLandscapeRight;
        [[UIDevice currentDevice] setValue:@(orientationTarget) forKey:@"orientation"];
    }
    //让屏幕方向与设备方向统一
    [UIViewController attemptRotationToDeviceOrientation];

遇到的问题

真机测试横屏失效 Xcode Version 14.3.1 (14E300c)
ios15.3 连接真机无法在xcode调试模式下横屏,停止运行后,手动启动app,横屏可以实现。
知道原因导致的,欢迎交流指导。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容