强制改变方向

时间:2011-12-21 17:50:54

标签: objective-c ios cocoa-touch uikit

我有一个基于标签的应用程序,其中一个选项卡在纵向和横向模式下均可用,所有其他选项卡仅以纵向显示。

我正在检查选中的按钮以允许在shouldAutorotateToInterfaceOrientation中旋转:但是当我处于横向模式时,当我选择不同的选项卡时,我需要加载该视图控制器,但也强制我的应用程序进入正常的纵向布局模式。

似乎没有明确的优先选择这样做,我尝试设置状态栏方向,但状态栏是唯一可移动的视觉元素。

任何提示和示例都会很棒,谢谢。

2 个答案:

答案 0 :(得分:7)

我能够做到这一点,但我现在警告你,这是一个黑客攻击。

首先,我为UITabBarController创建了一个名为的类别     UITabBarController+SelectiveRotation

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return [self.selectedViewController shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
}

这样,只要选定的选项卡允许方向,TabBar就可以自由旋转。确保在创建UITabBarController的任何地方(可能在您的应用程序代理中)导入此文件。

然后,我让我的AppDelegate使自己成为标签栏的代表,我实现了这个方法:

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    // this ensures that the view that will be shown is presented in a supportred rotation
    UIViewController *c = [[UIViewController alloc]init];
    [viewController presentModalViewController:c animated:NO];
    [viewController dismissModalViewControllerAnimated:NO];
    [c release];
    if ([UIViewController respondsToSelector:@selector(attemptRotationToDeviceOrientation)]) {
        // this ensures that the view will be presented in the orientation of the device
        // This method is only supported on iOS 5.0.  iOS 4.3 users may get a little dizzy.
        [UIViewController attemptRotationToDeviceOrientation];
    }
}

当选项卡更改时,第二位代码会强制标签栏旋转到可接受的方向。例如,如果您转到可以旋转的选项卡,然后转到横向,然后转到仅支持纵向的选项卡,它会强制将方向更改为纵向。在iOS 4.3及更早版本中,返回旋转的选项卡会将其显示在您离开它的方向上。我无法找到解决方法。

我做了所有这些因为这是客户要求,但我认为这实际上并不是一个非常实用的设计。我没有发现太多的视觉调整令人迷惑,但是通过这种方法迫使设备旋转是非常刺耳的,因为它是瞬间的。你可能想尝试一下,看看你对它的感受。

答案 1 :(得分:0)

我认为如果您只使用以下代码,它应该可以正常运行。

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
// this ensures that the view that will be shown is presented in a supportred rotation
UIViewController *c = [[UIViewController alloc]init];
[viewController presentModalViewController:c animated:NO];
[viewController dismissModalViewControllerAnimated:NO];
[c release];
if ([UIViewController respondsToSelector:@selector(attemptRotationToDeviceOrientation)]) {
    // this ensures that the view will be presented in the orientation of the device
    // This method is only supported on iOS 5.0.  iOS 4.3 users may get a little dizzy.
    [UIViewController attemptRotationToDeviceOrientation];
}

}