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

在AppDelegate中使用supportedInterfaceOrientationsForWindow控制旋转失效问题

问题分析与解决

先看你的代码:

@interface MyAppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
{
    NSInteger skipforeground;
    NSInteger allowLandscape;
    NSInteger NoCheck;
}
- (UIInterfaceOrientationMask)application:(UIApplication *) application
  supportedInterfaceOrientationsForWindow:(UIWindow *) window {
    
    if (self->allowLandscape) {
        NSLog(@"rotation yes !");
        return UIInterfaceOrientationMaskAll;
    } else
    {
        return UIInterfaceOrientationMaskPortrait;
    };
}

你遇到的核心矛盾,本质是两个关键点导致的:

1. 系统不会自动感知变量变化并重新查询方向支持

当你在其他代码位置修改allowLandscape的值后,iOS系统不会主动监测到这个变量的变更,自然不会重新调用supportedInterfaceOrientationsForWindow:方法。而用2>1这种恒真条件时,每次设备方向发生变化,系统都会调用这个方法并得到允许旋转的结果,所以旋转功能正常生效。

解决办法:修改allowLandscape的值后,主动触发系统重新检查屏幕方向,执行以下代码即可:

[UIViewController attemptRotationToDeviceOrientation];

这行代码会让系统立刻重新查询当前支持的屏幕方向,你的新返回值就能生效。

2. 额外排查:当前ViewController的旋转优先级更高

iOS中,当前显示的ViewController的旋转设置优先级高于AppDelegate。如果你的ViewController自己重写了supportedInterfaceOrientations方法,并且返回UIInterfaceOrientationMaskPortrait,那即使AppDelegate返回UIInterfaceOrientationMaskAll,屏幕也不会旋转。

检查当前活跃ViewController的代码,确认没有覆盖旋转相关方法,或者让ViewController的旋转逻辑和AppDelegate保持一致。

另外注意:allowLandscape是NSInteger类型,赋值时建议用整数1而非布尔值true(虽然OC里true等价于1,但避免类型混淆),比如:

self->allowLandscape = 1;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:01:44