强制改变方向

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

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

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

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

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

首先,我为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及更早版本中,返回旋转的选项卡会将其显示在您离开它的方向上。我无法找到解决方法。

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

我想如果你只是使用下面的代码,它应该运行良好。

 - (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]; } 

}