在 iOS 5.1 及更早的版本中,我們通常透過 shouldAutorotateToInterfaceOrientation: 來單獨控制某個 UIViewController 支援的旋轉方向,例如:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
然而在 iOS 6 中,這個方法已被弃用、不再生效。官方建議改用 supportedInterfaceOrientations 與 preferredInterfaceOrientationForPresentation。
但實測會發現,單靠覆寫 supportedInterfaceOrientations 並無法鎖定螢幕:
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
經過多次嘗試後,歸納出能真正控制旋轉支援方向的做法——繼承 UINavigationController 並加上以下方法:
- (BOOL)shouldAutorotate
{
return self.topViewController.shouldAutorotate;
}
- (NSUInteger)supportedInterfaceOrientations
{
return self.topViewController.supportedInterfaceOrientations;
}
接著將它設為程式入口,或指定為 self.window.rootViewController,再往裡面添加各自的 view controller。
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAllButUpsideDown;
}
- (BOOL)shouldAutorotate
{
return YES;
}
透過這套組合,就能對每一個 view controller 進行個別的旋轉控制。
若所有 view controller 都不需要旋轉,乾脆直接在 AppDelegate 統一鎖定:
- (NSUInteger)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return UIInterfaceOrientationMaskPortrait;
}