需求是:只有某一個頁面要支援橫屏,其餘全部鎖在豎屏。聽起來簡單,實作過程卻踩了好幾個坑,這裡完整記錄。
1. Info.plist(全版本可用):加入 Supported interface orientations 欄位,在裡頭補上要支援的方向。
2. AppDelegate(iOS 6 起):針對整個應用設定支援方向。
- (NSUInteger)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window {
return UIInterfaceOrientationMaskAll;
}
3. 重寫 shouldAutorotateToInterfaceOrientation:(iOS 5 及以前):
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
4. 重寫 supportedInterfaceOrientations 與 shouldAutorotate(iOS 6 起):
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskAllButUpsideDown;
}
- (BOOL)shouldAutorotate {
return YES;
}
前兩者是全域設定,後兩者作用在單一頁面。把全域與單頁的設定組裝起來,就能做到「只有某頁可旋轉」。
關鍵在於 UITabBarController 與 UINavigationController 自己回傳了方向遮罩,把子控制器的意圖蓋掉了。解法是改寫它們,把決定權交還給目前的子控制器。
有 UITabBarController 時,用 category 或繼承覆寫:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// 不支援舊版系統的話可省略這個方法
return [self.selectedViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}
- (NSUInteger)supportedInterfaceOrientations {
return [self.selectedViewController supportedInterfaceOrientations];
}
- (BOOL)shouldAutorotate {
return YES;
}
有 UINavigationController 時:
- (NSUInteger)supportedInterfaceOrientations {
return [self.topViewController supportedInterfaceOrientations];
}
- (BOOL)shouldAutorotate {
return YES;
}
接著,在需要旋轉的頁面實作:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskAllButUpsideDown;
}
- (BOOL)shouldAutorotate {
return YES;
}
不需要旋轉的頁面則是:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotate {
return NO;
}
頁面數量多時,建議抽一個基類把「鎖豎屏」的實作放進去,只有需要旋轉的頁面覆寫即可,不必每頁重複貼。
這個問題困擾我最久,但解決只花了几秒——我的手機長期開著「方向鎖定」,解開就一切正常。遇到「怎麼設都不會轉」時,先確認一下裝置與模擬器的方向鎖,能省下大量時間。
這牽涉到 Info.plist 與 AppDelegate 兩種設定的關係。兩者效果相同,都能擴充全域支援的方向,差異在於:AppDelegate 的實作只在 iOS 6 之後生效,若要支援更舊的系統,Info.plist 的欄位仍然必填。若兩邊都設了,支援方向以 AppDelegate 的程式碼為準;而啟動畫面的方向,取決於 Info.plist 中欄位的順序。
舉例:順序寫成 Landscape(right)、Landscape(left)、Portrait,啟動時就是橫屏;寫成 Portrait、Landscape(right)、Landscape(left),啟動時就是豎屏。
個人部落格:https://blog.csdn.net/zhaoxy2850
本文地址:https://blog.csdn.net/zhaoxy_thu/article/details/18412661