无法使用导航控制器在视图控制器上locking设备方向

我有一个推式导航堆栈中的9个视图控制器。 我想我所有的视图控制器被locking到肖像,但我的第四个视图控制器来支持所有的方向。 我已经尝试了许多方法,但是目前已经将支持全局的设备方向设置为纵向,并将这些代码添加到了我的第四个视图控制器中,以支持所有的方向。

-(NSUInteger)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskAll; } -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return (UIInterfaceOrientationPortrait | UIInterfaceOrientationLandscapeLeft | UIInterfaceOrientationLandscapeRight); } 

如果我在没有导航控制器的单个视图控制器上尝试它,它工作正常。 我也试图在所有的视图控制器上实现这些方法,设置全局设置来支持所有的方向,并添加代码来支持纵向方向,但无济于事。

这确实是可能的,而且我在我目前的一个项目中做了这个。 首先,您需要在项目常规选项卡中勾选您想要支持的所有方向选项。 其次,您将创build一个UINavigationController的子类,它将成为您的导航控制器,例如,如果您有一个带有导航控制器的Storyboard,则必须使用Interface Builder中的Identity Inspector选项卡制作您的自定义导航控制器。

你显然需要重写这样的子类中的一些方法,它们是:

 - (BOOL)shouldAutorotate { return YES; } 

这告诉导航控制器它需要允许视图控制器旋转。 之后,重写下面的方法,仔细阅读下面的实现:

 - (NSUInteger)supportedInterfaceOrientations { return [self.topViewController supportedInterfaceOrientations]; } 

这从它的topViewController(当前可见的)获取支持的接口方向。

所以你需要覆盖所有的视图控制器相同的方法如下:

 - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } 

这将locking自己的肖像,你想返回:

 UIInterfaceOrientationMaskSomethingDifferentFromPortrait 

这在我的情况是

 UIInterfaceOrientationMaskAllButUpsideDown 

希望能帮助到你。

尝试在你所有的视图控制器中使用它来解决他们的肖像,

  • (NSUInteger)应用程序:(UIApplication *)应用程序supportedInterfaceOrientationsForWindow:(UIWindow *)窗口{

     return UIInterfaceOrientationMaskPortrait; 

    }

为第四个viewController添加

  • (NSUInteger)应用程序:(UIApplication *)应用程序supportedInterfaceOrientationsForWindow:(UIWindow *)窗口{

     return UIInterfaceOrientationMaskAllButUpsideDown; 

    }