在 iOS 6 中,若 App 的根控制器是 UINavigationController,要實作特定頁面橫向或縱向顯示,需要讓 navigation controller 把方向判斷轉交給目前顯示的 view controller。
首先在 AppDelegate 中允許所有方向,由個別頁面自行決定。
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
return UIInterfaceOrientationMaskAll;
}可為 UINavigationController 建立 category,將方向相關方法轉發給 topViewController。
- (BOOL)shouldAutorotate {
return [[self topViewController] shouldAutorotate];
}
- (NSUInteger)supportedInterfaceOrientations {
return [[self topViewController] supportedInterfaceOrientations];
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
return [[self topViewController] preferredInterfaceOrientationForPresentation];
}在需要橫向的頁面中,可回傳橫向遮罩;若需要縱向,則改為縱向。
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscapeRight;
}
- (BOOL)shouldAutorotate {
return YES;
}頁面切換時,若需要讓方向設定正確生效,建議使用 presentViewController 呈現新的 navigation controller,而不是單純用 push 切換。
[self presentViewController:navigationController animated:YES completion:nil];