在 iPhone 上支持纵向模式,在 iPad 上支持横向+纵向模式的通用应用程序

Supporting Universal App with Portrait Orientation on iPhone and Landscape+Portrait on iPad

我需要我的应用在 iPad 和 iPhone 上兼容。它有一个 tabbarController 作为 rootViewController。

在 iPad 中,我需要它在横向和纵向上都可用。 在 iPhone 中,虽然我需要 rootView 本身是 Portrait 并且我确实有一些 viewControllers,它们在 tabbarController 上呈现,它们需要在横向和纵向中都可用(例如 viewController 用于播放来自 Youtube 的视频)。所以我如下锁定 tabbarController 的旋转(在 UITabbarController 子类中)。

# pragma mark - UIRotation Methods

- (BOOL)shouldAutorotate{
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);
}

- (NSUInteger)supportedInterfaceOrientations{
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? UIInterfaceOrientationMaskAll : UIInterfaceOrientationMaskPortrait;
}

我打算做的是通过锁定根 viewController(tabbarController) 的旋转,我锁定了 tabbarController 中的所有 VC(仅在 iPhone) 和显示在 tabbarController 顶部的视图可以根据设备方向旋转。

问题

在应用程序在 iPhone 中启动之前,一切都按预期进行。当以横向模式启动时,应用程序默认为横向并以非预期的横向模式启动应用程序。即使设备方向是横向,它也应该以纵向模式本身启动。由于我关闭了 iPhone 的自动旋转,因此该应用程序本身继续处于横向状态,从而导致错误。我尝试了这种方法来强制应用程序在 application:didFinishLaunchingWithOptions 中以纵向启动:

#pragma mark - Rotation Lock (iPhone)

- (void)configurePortraitOnlyIfDeviceIsiPhone{
    if ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone))
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
}

问题仍然存在。我已经为 iPad 和 iPhone 的 SupportedInterfaceOrientaions 键允许了 info.plist 上的所有方向选项,因为我需要应用程序在 iPhone 中横向显示,即使只有少数几个viewController秒。如果我能以某种方式强制该应用程序以纵向启动,即使设备方向是横向,这个问题也可以解决。如果逻辑有误,请纠正我,如果没有,我们将不胜感激任何帮助使应用程序以纵向模式启动的帮助。

我已经完成了 this question here and here,但还不能正常工作。

谢谢

这就是我设法让它工作的方法。在AppDelegate.m中,我添加了这个方法。

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    //if iPad return all orientation
    if ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad))
        return UIInterfaceOrientationMaskAll;

    //proceed to lock portrait only if iPhone
    AGTabbarController *tab = (AGTabbarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    if ([tab.presentedViewController isKindOfClass:[YouTubeVideoPlayerViewController class]])
        return UIInterfaceOrientationMaskAllButUpsideDown;
    return UIInterfaceOrientationMaskPortrait;
}

此方法会在每次显示视图时检查方向并根据需要更正方向。我 return iPad 的所有方向和 iPhone 的 none 除了要呈现的视图(应该旋转的视图,YouTubeVideoPlayerViewController)被关闭.

并且在tabbarController子类中,

# pragma mark - UIRotation Methods

- (BOOL)shouldAutorotate{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations{
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? UIInterfaceOrientationMaskAll : UIInterfaceOrientationMaskPortrait;
}

问题是,当我们return 不使用 shouldAutoRotate 时,应用程序将忽略所有旋转更改通知。它应该 return YES 以便它旋转到 supportedInterfaceOrientations

中描述的正确方向

我想这就是我们应该如何处理这个要求,而不是像许多帖子在 SO 上所说的那样将旋转指令传递给相应的 viewControllers。这是使用 Apple 推荐的容器的一些优势,这样我们就不必在容器中的每个视图上编写旋转指令。