iOS16下Objective-C实现横竖屏切换的解决方案咨询
解决iOS16下Objective-C锁定横竖屏失效问题
你的代码核心问题
- 类型不匹配:
perference.interfaceOrientations需要的是UIInterfaceOrientationMask枚举值,你写的1 < deviceOrientation是布尔表达式,这是代码无法运行的直接原因。 - API废弃:
[UIApplication sharedApplication].statusBarOrientation在iOS13后已被废弃,应该从UIWindowScene获取当前界面方向。 - 场景获取不严谨:直接取第一个
connectedScenes可能拿到非活跃场景,需筛选出当前活跃的UIWindowScene。
修正后的完整Objective-C实现
以下是可正常锁定指定方向的代码,以锁定横屏为例:
// 获取当前活跃的UIWindowScene UIWindowScene *activeWindowScene = nil; for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) { if (scene.activationState == UISceneActivationStateForegroundActive && [scene isKindOfClass:[UIWindowScene class]]) { activeWindowScene = (UIWindowScene *)scene; break; } } if (!activeWindowScene) { NSLog(@"无法获取活跃的WindowScene"); return; } // 定义要锁定的方向,可按需修改 UIInterfaceOrientationMask targetOrientationMask; // 锁定横屏右 targetOrientationMask = UIInterfaceOrientationMaskLandscapeRight; // 锁定横屏左:UIInterfaceOrientationMaskLandscapeLeft // 锁定竖屏:UIInterfaceOrientationMaskPortrait UIWindowSceneGeometryPreferencesIOS *preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init]; preferences.interfaceOrientations = targetOrientationMask; [activeWindowScene requestGeometryUpdateWithPreferences:preferences errorHandler:^(NSError * _Nonnull error) { NSLog(@"锁定方向失败:%@", error.localizedDescription); }];
额外注意事项
- Info.plist配置:确保项目Info.plist中已添加需要支持的方向(如横屏),否则
requestGeometryUpdateWithPreferences会报错。 - RN线程处理:如果在RN原生模块中使用,需在主线程执行方向锁定操作,可用
dispatch_async(dispatch_get_main_queue(), ^{ ... });包裹代码。 - Swift转Objective-C参考:若你有Swift完整解决方案,可通过Xcode的
Editor -> Convert to Objective-C功能自动转换,避免手动转换出错。
内容的提问来源于stack exchange,提问作者Btbrad
相关产品推荐
相关产品推荐

