iOS 6:将视图控制器推入导航控制器堆栈时如何强制更改方向

时间:2013-05-04 04:08:21

标签: ios xcode ios6 uinavigationcontroller orientation

我认为这个问题现在应该被问过一百万次,但我仍然无法找到答案。

这是我的层次结构:UINavigationController - > UIViewController 1 - >(推) - > UIViewController 2

UINavigationController:支持所有可能的方向 UIViewController 1:仅支持肖像 UIViewController 2:仅支持横向

如何仅将UIViewController 1锁定为纵向,同时仅将UIViewController 2锁定为横向?它甚至可能吗?到目前为止,我看到的是UIViewController 2总是采用UIViewController 1的方向。

请注意,这仅适用于iOS 6。

谢谢!

3 个答案:

答案 0 :(得分:13)

我也发现了同样的问题。我发现每次都不应该调用此功能,所以我改变方向编程

首先导入此

#import <objc/message.h>

然后

-(void)viewDidAppear:(BOOL)animated
{

     if(UIDeviceOrientationIsPortrait(self.interfaceOrientation)){
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)])
        {
            objc_msgSend([UIDevice currentDevice], @selector(setOrientation:), UIInterfaceOrientationLandscapeLeft );


        }
    }

}

希望这对你有所帮助。

答案 1 :(得分:9)

添加新的Objective-C类(UINavigationController的子类)并将以下代码添加到.m文件

-(NSUInteger)supportedInterfaceOrientations
 {
     NSLog(@"supportedInterfaceOrientations = %d ", [self.topViewController         supportedInterfaceOrientations]);

     return [self.topViewController supportedInterfaceOrientations];
 }

-(BOOL)shouldAutorotate
  {
     return self.topViewController.shouldAutorotate;
  }

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
  {
    // You do not need this method if you are not supporting earlier iOS Versions

    return [self.topViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
  }

添加新类后,转到ViewController类并进行以下更改

- (BOOL)shouldAutorotate  // iOS 6 autorotation fix
  {
    return YES;
  }
- (NSUInteger)supportedInterfaceOrientations // iOS 6 autorotation fix
  {
      return UIInterfaceOrientationMaskAll;
  }

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation // iOS 6 autorotation fix
  {
      return UIInterfaceOrientationPortrait;
  }
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
  {
      return YES;
  }

enter image description here

在shouldAutorotate中,shouldAutorotateToInterfaceOrientation:如果你想让ViewController支持多个方向,则返回YES,否则返回NO,同样在houldAutorotateToInterfaceOrientation中:方法传递你想要的特定ViewController的Orintation,对所有视图控制器重复相同的操作。

这样做的原因: -

1:虽然您可以将所有viewController的preferredInterfaceOrientationForPresentation更改为特定方向,但由于您使用的是UINavigationController,因此您还需要覆盖UINavigationController的supportedInterfaceOrientations

2:为了覆盖UINavigationController的supportedInterfaceOrientations,我们已经将UINavigationController子类化,并修改了与UINavigation Orientation相关的方法。

希望它会对你有所帮助!

答案 2 :(得分:1)

使应用程序仅支持纵向模式,并将以下行添加到UIViewController 2的initWithNibName

self.view.transform = CGAffineTransformMakeRotation(M_PI/2);