需求很常見:App 本身只支援直向(Portrait),但內嵌網頁裡的影片一按全螢幕,就應該自動轉成橫向觀看。做法是透過播放器的通知,動態改變 App 支援的方向。
這個方法由系統在需要決定方向時主動呼叫,不必擔心呼叫時機:
// 為影片旋轉做準備
- (NSUInteger)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
if (_isFull)
return UIInterfaceOrientationMaskAll;
return UIInterfaceOrientationMaskPortrait;
}
配套的標頭檔宣告一個全域旗標:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
BOOL _isFull; // 是否處於全螢幕播放
}
@property (nonatomic) BOOL isFull;
@end
只要在需要旋轉的地方改動這個旗標,並觸發系統重新詢問方向,畫面就會跟著轉。
// 進入全螢幕
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(videoStarted:)
name:@"UIMoviePlayerControllerDidEnterFullscreenNotification"
object:nil];
// 退出全螢幕
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(videoFinished:)
name:@"UIMoviePlayerControllerWillExitFullscreenNotification"
object:nil];
這裡有個實務上的坑:網路上不少範例用的是 DidExitFullscreenNotification,但實測退出時畫面不會復原。真正該搭配的是 WillExitFullscreenNotification,請特別留意。
#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];
}
}
videoFinished 執行完畢後,系統會重新呼叫 AppDelegate 中的 supportedInterfaceOrientationsForWindow,此時 isFull 已被設回 NO,方向便回復為僅支援直向。
這個套路並不限於影片。任何「App 整體鎖定單一方向,但某幾個頁面需要特殊方向」的需求,都能用同一個旗標加通知的組合解決。需要注意的是 setOrientation: 屬於私有 API,若要送審 App Store,建議改用新版的關鍵字旗標或 Scene 相關 API 來達到同樣效果。