推送到导航控制器堆栈的每个视图控制器都必须支持相同的方向。这意味着不可能有一些视图控制器只支持纵向,而另一些只支持横向。换句话说,同一个导航控制器堆栈上的所有视图控制器都应该在委托中返回相同的结果:
(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
但是有一个简单的解决方案!这是一个从纵向到横向的示例。这是执行此操作的步骤,下面是支持它的代码。
- 创建一个“假”视图控制器,它将作为子导航控制器的根。这个视图控制器应该支持横向。
- 创建 a 的新实例
UINavigationController
,将“假”视图控制器的实例添加为 root,并将横向视图控制器的实例添加为第二个视图控制器
UINavigationController
从父视图控制器将实例呈现为模态
首先,使用以下代码创建一个新的视图控制器(FakeRootViewController):
@interface FakeRootViewController : UIViewController
@property (strong, nonatomic) UINavigationController* parentNavigationController;
@end
@implementation FaceRootViewController
@synthesize parentNavigationController;
// viewWillAppear is called when we touch the back button on the navigation bar
(void)viewWillAppear:(BOOL)animated {
// Remove our self from modal view though the parent view controller
[parentNavigationController dismissModalViewControllerAnimated:YES];
}
(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationIsLandscape(interfaceOrientation));
}
这是呈现您希望在横向模式下显示的视图控制器的代码:
FakeRootViewController* fakeRootViewController = [[FakeRootViewController alloc] init];[fakeRootViewController.navigationItem setBackBarButtonItem:backButton]; // Set back button
// The parent navigation controller is the one containing the view controllers in portrait mode.
fakeRootViewController.parentNavigationController = parentNavigationController;
UINavigationController* subNavigationController = // Initialize this the same way you have initialized your parent navigation controller.
UIViewController* landscapeViewController = // Initialize the landscape view controller
[subNavigationController setViewControllers:
[NSArray arrayWithObjects:fakeRootViewController,
landscapeViewController, nil] animated:NO];
[_navigationController presentModalViewController:subNavigationController animated:YES];
请记住,landscapeViewController 也应该有这个实现:
(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationIsLandscape(interfaceOrientation));
}