iOS 裡做屏幕旋轉,最惱人的場景莫過於:整個 App 默認豎屏,只有個別頁面需要橫屏,而且還要求「同一個頁面可以隨時在橫豎屏之間切換」,像視頻播放器那樣。
下面這套思路在 Swift 和 Objective-C 中是通用的,核心只有一個開關變量。
先定義一個標誌位,用來表示「當前是否允許旋轉」:
var blockRotation: Bool = false
然後實現_supportedInterfaceOrientationsForWindow_這個方法,由這個開關決定當前支持的屏幕方向:
func application(application: UIApplication,
supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
if self.blockRotation {
return UIInterfaceOrientationMask.All
} else {
return UIInterfaceOrientationMask.Portrait
}
}
這一步是整個方案的樞紐:系統查詢「這個窗口支持哪些方向」時,實際上問的就是這裡。
1. 拿到 AppDelegate 引用
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
2. 在 viewDidLoad 中打開開關
override func viewDidLoad() {
super.viewDidLoad()
appDelegate.blockRotation = true
}
3. 在 viewWillAppear 中主動切到橫屏
override func viewWillAppear(animated: Bool) {
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
4. 在 viewWillDisappear 中恢復豎屏
override func viewWillDisappear(animated: Bool) {
appDelegate.blockRotation = false
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
注意這裡的順序:先把開關關掉,再把方向擰回豎屏。如果顛倒過來,系統可能來不及響應新的方向約束。
5. 是否響應重力自動旋轉
// 如果希望完全由代碼控制、不跟隨重力感應,返回 false
override func shouldAutorotate() -> Bool {
return false
}
上面的例子處理的是「豎屏頁面跳轉到橫屏頁面」。但真實需求往往是:一個頁面默認豎屏,點一下按鈕就變橫屏——這才是視頻播放器的典型交互。
做法是把方向切換封裝成兩個方法,隨時調用:
// MARK: - 橫屏
func hengp() {
appDelegate.blockRotation = true
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
// MARK: - 豎屏
func shup() {
appDelegate.blockRotation = false
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
這兩個方法本質上和 viewWillAppear / viewWillDisappear 裡做的是同一件事,只是把觸發時機交給了用戶操作。
旋轉前後通常需要重排界面,這兩個回調可以幫上忙:
// 即將開始旋轉
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation,
duration: NSTimeInterval) {
}
// 旋轉完成,在這裡重新佈局
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
// 獲取當前的物理屏幕方向
let interfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
if interfaceOrientation == UIInterfaceOrientation.Portrait {
// 當前是豎屏
print("豎屏")
} else {
// 當前是橫屏,重新鋪滿
self.theWebView?.frame = self.view.frame
}
}
請記住:旋轉之後,屏幕的寬高值會發生變化。
如果你的代碼裡緩存過寬高,橫屏之後再讀取,拿到的仍然是豎屏時代的舊值,佈局必然錯亂。所以在 didRotateFromInterfaceOrientation 這類時機,一定要重新取一次:
let bWidth = CGRectGetWidth(UIScreen.mainScreen().bounds) // 屏幕寬度
let bHeight = CGRectGetHeight(UIScreen.mainScreen().bounds) // 屏幕高度
更好的習慣是乾脆不緩存——每次需要時直接從 UIScreen.mainScreen().bounds 或 self.view.bounds 讀取,從源頭上杜絕這類問題。
另外提醒一句:UIDevice.setValue(_:forKey:) 屬於私有接口,App Store 審核存在風險。如果是正式上線的項目,更穩妥的路徑是結合 AppDelegate 的方向約束 + requestGeometryUpdate(新系統)或 attemptRotationToDeviceOrientation 來實現,並把 shouldAutorotate 的返回值交給具體的 view controller 決策。