您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 6 的橫向/縱向切換處理(含 UINavigationController)

編輯:iOS 相關資訊

iOS 6 之後,介面方向的控制權交給了 supportedInterfaceOrientations 與 shouldAutorotate。問題是當根控制器是 UINavigationController 時,系統只會詢問導航控制器本身,子頁面的設定往往不會生效。以下是完整的處理步驟。

步驟一:在 AppDelegate 開放所有方向

- (NSUInteger)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskAll;
}

步驟二:為 UINavigationController 加上 category 轉發詢問

讓導航控制器把方向的決定權交給目前最上層的 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 中集中管理,會比逐頁覆寫更清楚。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved