在iOS 7上禁用单个呈现ViewController的自动旋转
我有一个UIViewController
,它以模态方式呈现(全屏),我想在该视图中禁用自动旋转。我不想将它限制为横向或纵向,只是希望它保持原来呈现的任何方向。在iOS 7上禁用单个呈现ViewController的自动旋转
在iOS 6上是足够的,只是覆盖的方法:
- (BOOL)shouldAutorotate {
return NO;
}
而且这也正是我想要的。然而,在iOS 7上,这似乎没有效果。该方法确实被调用,但返回值似乎被操作系统忽略 - 无论如何它都会自动旋转。
该文档没有提及此方法的任何更改。我如何在iOS 7上实现预期的效果?
编辑:正被呈现的视图控制器(未被推!)通过UINavigationViewController
:
[self.navigationController presentViewController:vc animated:YES completion:nil];
解决方案:
作为奇数,因为它看起来,但是这种解决方案没有公布在关于此主题的众多现有问题。在iOS 7上,似乎UINavigationController
给出的答案是 shouldAutorotate
是操作系统的作用。我们需要子类UINavigationController
来修改其行为。
当处理常规导航堆栈时,仅使用[self.topViewController shouldAutorotate]
就足够了,但是当存在模态视图时,它驻留在self.presentedViewController
中,而不是self.topViewController
。因此,完整的解决方案是这样的:
- (BOOL)shouldAutorotate {
UIViewController *vc;
if (self.presentedViewController) vc = self.presentedViewController;
else vc = [self topViewController];
return [vc shouldAutorotate];
}
#import <objc/message.h>
-(void)viewDidAppear:(BOOL)animated{
objc_msgSend([UIDevice currentDevice], @selector(setOrientation:), UIInterfaceOrientationPortrait);
}
看到How do I programmatically set device orientation in iOS7?
但由于它是一个私有API,你的应用程序可以通过苹果公司拒绝把你正在使用这种方法的情况。所以,也许最好从项目详细信息 - >常规 - >部署信息选项卡中设置方向,只选择横向左和横向右选择。如果你的所有观点只需要一种方向,这可能是更好的方法。
调用私有API可能会导致您的应用程序被拒绝。 –
你不注意。 obj/message.h实际上包含在Apple的示例中,请参阅http://www.opensource.apple.com/source/objc4/objc4-371.1/runtime/message.h – user3344236
我知道'objc_msgSend'很好。调用'setOrientation:'是问题,因为'UIDevice'上的orientation属性被声明为只读。 –
所以我只是试过你的代码,它的工作使我相信你在UINavigationController
中提出你的UIViewController
。无论出于何种原因,iOS 7都改变了UINavigationController
处理旋转的方式。
最简单的解决方案是创建一个UINavigationController
的子类,它覆盖shouldAutorotate
方法并从topViewController返回值。
@interface CustomNavigationController : UINavigationController
@end
@implementation CustomNavigationController
- (BOOL)shouldAutorotate
{
return [[self topViewController] shouldAutorotate];
}
@end
所以不是这样,其中viewController
是你的对象,对于shouldAutorotate
返回NO
。
UINavigaitonController *navController = [UINavigationController alloc] initWithRootViewController:viewController];
[self presentViewController:navController animated:YES completion:nil];
你会使用CustomNavigationController代替
CustomNavigationController *customNavController = [CustomNavigationController alloc] initWithRootViewController:viewController];
[self presentViewController:customNavController animated:YES completion:nil];
iOS7使用视图控制器方法'supportedInterfaceOrientations'控制自转过程,就像早期版本中使用'shouldAutorotateToInterfaceOrientation:'你也可能会遇到的问题,如果你在'UITabController'中展示视图控制器。 –
你的'UIViewController'是否出现在'UINavigationController'中? –
可能的重复http://stackoverflow.com/questions/12520030/how-to-force-a-uiviewcontroller-to-portait-orientation-in-ios-6 –