有些情境需要 App 主動把畫面轉成橫向,例如播放影片或查看寬幅圖表。做法是先改狀態列方向,再對 view 做反向旋轉,兩者搭配才不會出現「內容轉了、狀態列沒轉」的怪狀態。
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft animated:YES];
CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:duration];
view.transform = CGAffineTransformMakeRotation(-M_PI / 2);
[UIView commitAnimations];
為什麼是 -M_PI / 2?Core Graphics 的旋轉以弧度為單位,逆時針為正。UIInterfaceOrientationLandscapeLeft 代表 home 鍵在右側,畫面內容需要順時針轉 90 度才能視覺上「扶正」,因此這裡取負值。
動畫時間直接沿用系統的 statusBarOrientationAnimationDuration,轉屏動畫就會跟系統一致,不會出現突兀的跳動。
要留意的是,這種直接改 transform 的做法繞過了系統正常的轉向流程,因此:記得在不需要時把 transform 重設為 CGAffineTransformIdentity,否則離開該頁後畫面會歪掉。此外,你的 view controller 必須在 shouldAutorotateToInterfaceOrientation: 中允許橫向,否則系統層級仍會把畫面轉回來。
相較之下,較現代的作法是透過 UIDevice 送出 orientation change 通知,或直接以 supportedInterfaceOrientations 宣告支援方向並交由系統處理。上面這段程式碼的價值在於「手動控制時機」——例如使用者點了全螢幕按鈕才轉,這種需求就必須自己動手。
內容雖少,卻很實用,一點一點累積起來就是自己的工具庫。