【问题标题】:Manually set interface orientation手动设置界面方向
【发布时间】:2011-08-31 21:57:49
【问题描述】:

有没有简单的方法来手动设置界面的方向?即使在加载过程中设备方向可能是横向的,我也需要将界面设置为纵向。有点想远离 CGAffineTransforms。

【问题讨论】:

    标签: ios ios-4.2 ios4


    【解决方案1】:

    我知道的一种对我有用的方法(有点小技巧,可以在更改为您想要的方向之前显示一个方向)是:

    - (void)viewDidAppear:(BOOL)animated 
    {
        [super viewDidAppear:animated];
    
        UIApplication* application = [UIApplication sharedApplication];
    
        if (application.statusBarOrientation != UIInterfaceOrientationPortrait)
        {
            UIViewController *c = [[UIViewController alloc]init];
            [self presentModalViewController:c animated:NO];
            [self dismissModalViewControllerAnimated:NO];
            [c release];
        }
    }
    

    【讨论】:

    • 这实际上非常适合我描述的情况。但由于某种原因,尝试从纵向模式强制横向效果不佳(将 UIInterfaceOrientationPortrait 更改为 UIInterfaceOrientationLandscapeLeft)。想法?
    • 我不知道 Dan​​,你必须自己尝试通过创建一个子类 UIViewController 来处理 'shouldAutorotateToInterfaceOrientation:' 方法中的景观。
    • @ShanePowell,您的代码在 iOS6 之前运行良好。 iOS6有这样的技巧吗?
    【解决方案2】:

    首先,将您的应用和视图设置为仅支持纵向,然后使用从我的重构库es_ios_utils 中获取的此类别方法:

    @interface UIViewController(ESUtils)
        // Forces without using a private api.
        -(void)forcePortrait;
    @end
    
    @implementation UIViewController(ESUtils)
    
    -(void)forcePortrait
    {
        //force portrait orientation without private methods.
        UIViewController *c = [[UIViewController alloc] init];
        [self presentModalViewController:c animated:NO];
        [self dismissModalViewControllerAnimated:NO];
        [c release];
    }
    
    @end
    

    在帧完成之前关闭的视图将不会显示。

    【讨论】:

    • 我可能是从 Shane 或其他任何来源那里得到的。他的更完整一点,我的建议使用一个类别来重用。
    • 纵向是未扩展的 UIViewController 的默认支持方向,并且呈现它将强制一个有效的方向。
    【解决方案3】:

    覆盖它以控制方向直到加载...

    -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
    

    【讨论】:

    • 是的,你是对的。我的错。我更新了我的答案。您可以考虑只覆盖 shouldAutorotateToInterfaceOrientation 并根据需要保持方向。