iOS 6 之後,介面方向的控制權交給了 supportedInterfaceOrientations 與 shouldAutorotate。問題是當根控制器是 UINavigationController 時,系統只會詢問導航控制器本身,子頁面的設定往往不會生效。以下是完整的處理步驟。
- (NSUInteger)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return UIInterfaceOrientationMaskAll;
}
讓導航控制器把方向的決定權交給目前最上層的 view controller:
-(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;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}
這是最容易被忽略的一點:頁面之間若用導航控制器的 push/pop 切換,方向設定容易失效,改用模态呈現則能正確套用:
[self presentViewController:navigationController animated:YES completion:nil];
整體思路是「AppDelegate 開放權限 → 導航控制器轉發詢問 → 個別頁面宣告支援方向」。範例中的 shouldAutorotateToInterfaceOrientation: 屬於 iOS 5 時代的舊 API,在 iOS 6 之後已不再被呼叫,保留只是為了相容舊專案,實際上可以刪除。若專案已支援 iOS 8 以後的版本,還可改用 traitCollection 或直接把方向需求宣告在 AppDelegate 中集中管理,會比逐頁覆寫更清楚。