在iPhone上支持纵向方向的通用应用程序,在iPad上支持横向和纵向方向的通用应用程序

5
我希望我的应用程序能够在iPad和iPhone上同时兼容。它的根视图控制器是tabbarController。
在iPad上,我需要它可以在横屏和竖屏模式下使用。 在iPhone上,我需要根视图控制器始终为竖屏,并且我有一些视图控制器被呈现在tabbarController上,这些视图控制器需要在横屏和竖屏模式下都可用(例如,一个用于播放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;
}

我打算通过锁定rootViewController(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];
}

问题仍然存在。 我已经在info.plist的SupportedInterfaceOrientaions键上为iPad和iPhone允许了所有方向选项,因为即使只有少数viewControllers需要,在iPhone上我需要应用程序处于横向状态。 如果可以通过某种方式强制该应用程序在纵向方向启动,即使设备方向为横向,就可以解决此问题。 如果我的逻辑有误,请纠正我,如果没有,任何帮助使应用程序以纵向模式启动都将不胜感激。

我已经阅读了这里的问题这里, 但还没有解决问题。

谢谢

1个回答

4
这是我成功使其工作的方法。在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;
}

这个方法会在每次显示视图时检查方向,并根据需要进行更正。对于iPad,我返回所有方向,而对于iPhone,则不返回任何方向,但有一个例外,即要呈现的视图(应该旋转的视图,即YouTubeVideoPlayerViewController)被省略掉。
在tabbarController子类中,也需要进行相应的调整。
# pragma mark - UIRotation Methods

- (BOOL)shouldAutorotate{
    return YES;
}

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

问题在于,当我们返回NO给shouldAutoRotate时,应用程序将忽略所有旋转更改通知。应该返回YES,以便它会旋转到supportedInterfaceOrientations中描述的正确方向。
我认为这是我们应该处理此要求的方式,而不是像许多帖子在SO上所说的将旋转指令传递给各自的视图控制器。这是使用容器的一些优点,正如苹果建议的那样,这样我们就不必在容器中的每个视图上编写旋转指令了。

非常理解,我会去实现这个。谢谢你,我一直在寻找这样的解决方案,可以在AppDelegate中实现,而不需要在所有视图控制器中编写代码。 - Arpit B Parekh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接