【问题标题】:Set allowed orientations programmatically以编程方式设置允许的方向
【发布时间】:2026-01-23 05:55:01
【问题描述】:

嘿,我尝试设置允许的方向,但它不起作用。

AppDelegate.m:

- (NSUInteger)supportedInterfaceOrientations
    {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        return UIInterfaceOrientationMaskAll;
        }else{
        return UIInterfaceOrientationMaskPortrait;
        }

    }

在我的 Info.plist 中,我激活了所有方向。

【问题讨论】:

    标签: ios objective-c xcode ios7 ios8


    【解决方案1】:

    如果您希望您的应用旋转,您需要在应用的每个视图控制器中设置旋转。

    可能有必要为您的UINavigationControllerUITabBarController 创建一个自定义类,以使所有内容都按照您对这种代码的想法进行旋转:

    @implementation CustomTabBarController
    
    -(BOOL)shouldAutorotate
    {
        if(self.viewControllers && self.selectedIndex<self.viewControllers.count)
            return ((UIViewController*)self.viewControllers[self.selectedIndex]).shouldAutorotate;
        return NO;
    }
    
    -(NSUInteger)supportedInterfaceOrientations
    {
        if(self.viewControllers && self.selectedIndex<self.viewControllers.count)
            return ((UIViewController*)self.viewControllers[self.selectedIndex]).supportedInterfaceOrientations;
        return UIInterfaceOrientationMaskPortrait;
    }
    
    @end
    

    @implementation CustomNavigationController
    
    - (BOOL)shouldAutorotate
    {
        return self.topViewController.shouldAutorotate;
    }
    - (NSUInteger)supportedInterfaceOrientations
    {
        return self.topViewController.supportedInterfaceOrientations;
    }
    
    @end
    

    通过这两个自定义类,您可以直接从ViewController 本身处理您的应用是否应该旋转,这样就很方便了。

    【讨论】:

    • 我想旋转。我想设置允许的演说。是否可以在应用程序委托中说我支持 iOS8 和整个应用程序的旧版本?
    • 您需要为应用程序的每个视图控制器设置允许的方向(或使用继承仅定义一次),但要使其工作,您必须在 TabBar 和 navigationBar 中定义它(如果符合条件)。