需求是這樣的:整個 App 鎖定豎屏,不允許旋轉,但在用 UIWebView 播放視頻時,希望能全屏橫向觀看。
思路其實可以推廣——任何你想做「頁面級自動旋轉」的地方,都能套用這套做法。核心只有兩件事:一個全局開關,加上兩個播放通知。
先在 AppDelegate 的頭文件中聲明一個全局標誌位,用來標記當前是否處於全屏播放狀態:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
BOOL _isFull; // 是否全屏
}
接著實現 application:supportedInterfaceOrientationsForWindow:。這個方法系統會在屏幕旋轉等時機自動調用,不必擔心調用時機的問題:
// 為視頻旋轉做準備
- (NSUInteger)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (_isFull) {
return UIInterfaceOrientationMaskAll;
}
return UIInterfaceOrientationMaskPortrait;
}
邏輯很清晰:標誌位為真時開放所有方向,否則維持豎屏鎖定。
接下來在需要旋轉的頁面裡注册通知,讓系統在播放器進入與退出全屏時自動切換標誌位:
// 播放器即將進入全屏
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(videoStarted:)
name:@"UIMoviePlayerControllerDidEnterFullscreenNotification"
object:nil];
// 播放器即將退出全屏
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(videoFinished:)
name:@"UIMoviePlayerControllerDidExitFullscreenNotification"
object:nil];
這裡踩過一個坑:網上不少文章寫的是 UIMoviePlayerControllerDidExitFullscreenNotification,但實測並不生效,應該改用 WillExit 版本的通知,也就是 UIMoviePlayerControllerWillExitFullscreenNotification。
兩個回調方法都很短。開始播放時把標誌位置為 YES:
#pragma mark - 視頻通知的處理
- (void)videoStarted:(NSNotification *)notification {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.isFull = YES;
}
播放結束時把標誌位復位,並順手把設備方向強制掰回豎屏:
- (void)videoFinished:(NSNotification *)notification {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.isFull = NO;
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val = UIInterfaceOrientationPortrait;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
}
這裡之所以用 NSInvocation 而不是直接調用,是因為 setOrientation: 是 UIDevice 的私有方法,用消息表達式動態調可以避免編譯期警告。
執行完這兩個方法後,系統會自動觸發 AppDelegate 中的 supportedInterfaceOrientationsForWindow:,從而其實並沒有「強制旋轉」的代碼,方向變化完全由系統依據 isFull 的返回值決定。
除了上面的通知方案,也有人選擇直接操作 transform,把 rootViewController 的視圖整體旋轉 90 度,同時手動修正 frame 並設置 setStatusBarOrientation:。這種做法實現起來直觀,但副作用不少:狀態欄方向、鍵盤佈局、子視圖坐標都可能出錯,而且依賴私有 API 的行為在不同系統版本上並不穩定。
因此,如果項目允許,更推薦的還是本文的通知方案;而在 iOS 更晚的版本中,這類需求應該改用 AVPlayerViewController 或 AVPlayerLayer 配合 videoGravity 來實現,UIWebView 加 MPMoviePlayerController 的通知判斷已經屬於歷史方案了。