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

iOS 6 的螢幕旋轉控制技巧

編輯:iOS 相關資訊

在 iOS 5.1 及更早的版本中,我們通常透過 shouldAutorotateToInterfaceOrientation: 來單獨控制某個 UIViewController 支援的旋轉方向,例如:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

然而在 iOS 6 中,這個方法已被弃用、不再生效。官方建議改用 supportedInterfaceOrientations 與 preferredInterfaceOrientationForPresentation。

但實測會發現,單靠覆寫 supportedInterfaceOrientations 並無法鎖定螢幕:

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

可行方案:子類化 UINavigationController

經過多次嘗試後,歸納出能真正控制旋轉支援方向的做法——繼承 UINavigationController 並加上以下方法:

- (BOOL)shouldAutorotate
{
    return self.topViewController.shouldAutorotate;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return self.topViewController.supportedInterfaceOrientations;
}

接著將它設為程式入口,或指定為 self.window.rootViewController,再往裡面添加各自的 view controller。

禁止某個 view controller 旋轉(全版本通用)

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (BOOL)shouldAutorotate
{
    return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

開啟某個 view controller 的全部方向(不含顛倒)

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}
- (BOOL)shouldAutorotate
{
    return YES;
}

透過這套組合,就能對每一個 view controller 進行個別的旋轉控制。

補充:整個 App 都不支援旋轉

若所有 view controller 都不需要旋轉,乾脆直接在 AppDelegate 統一鎖定:

- (NSUInteger)application:(UIApplication *)application
    supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved