You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS16下Objective-C实现横竖屏切换的解决方案咨询

解决iOS16下Objective-C锁定横竖屏失效问题

你的代码核心问题

  1. 类型不匹配:perference.interfaceOrientations需要的是UIInterfaceOrientationMask枚举值,你写的1 < deviceOrientation是布尔表达式,这是代码无法运行的直接原因。
  2. API废弃:[UIApplication sharedApplication].statusBarOrientation在iOS13后已被废弃,应该从UIWindowScene获取当前界面方向。
  3. 场景获取不严谨:直接取第一个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);
}];

额外注意事项

  1. Info.plist配置:确保项目Info.plist中已添加需要支持的方向(如横屏),否则requestGeometryUpdateWithPreferences会报错。
  2. RN线程处理:如果在RN原生模块中使用,需在主线程执行方向锁定操作,可用dispatch_async(dispatch_get_main_queue(), ^{ ... });包裹代码。
  3. Swift转Objective-C参考:若你有Swift完整解决方案,可通过Xcode的Editor -> Convert to Objective-C功能自动转换,避免手动转换出错。

内容的提问来源于stack exchange,提问作者Btbrad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:40:42