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

iOS16屏幕旋转适配故障求助(Objective-C开发环境)

iOS 16 屏幕旋转故障修复方案

问题背景

已针对iOS 16的屏幕旋转逻辑做适配,但故障仍未解决,项目使用Objective-C开发。当前使用的代码存在逻辑错误,导致旋转请求失效。

当前代码的错误点

  • 类型不匹配:perference.interfaceOrientations需要赋值UIInterfaceOrientationMask枚举类型,但现有代码中1 < deviceOrientation是布尔值,无法正确传递旋转方向参数。
  • WindowScene获取不严谨:直接取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) {
    UIWindowSceneGeometryPreferencesIOS *preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
    // 根据设备方向转换为对应的界面旋转掩码
    UIInterfaceOrientationMask targetMask;
    switch (deviceOrientation) {
        case UIDeviceOrientationPortrait:
            targetMask = UIInterfaceOrientationMaskPortrait;
            break;
        case UIDeviceOrientationLandscapeLeft:
            targetMask = UIInterfaceOrientationMaskLandscapeLeft;
            break;
        case UIDeviceOrientationLandscapeRight:
            targetMask = UIInterfaceOrientationMaskLandscapeRight;
            break;
        case UIDeviceOrientationPortraitUpsideDown:
            targetMask = UIInterfaceOrientationMaskPortraitUpsideDown;
            break;
        default:
            targetMask = UIInterfaceOrientationMaskPortrait;
            break;
    }
    preferences.interfaceOrientations = targetMask;
    
    [activeWindowScene requestGeometryUpdateWithPreferences:preferences errorHandler:^(NSError * _Nonnull error) {
        NSLog(@"旋转请求错误--%@", error);
    }];
}

额外注意事项

  • 确认Info.plist中已配置UISupportedInterfaceOrientations(iPhone)和UISupportedInterfaceOrientations~ipad(iPad),添加需要支持的旋转方向。
  • ViewController中仍需实现supportedInterfaceOrientations和shouldAutorotate方法,iOS 16仍依赖这些方法做旋转权限判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:45:35