您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

整個 App 鎖定直向,卻要讓 UIWebView 影片全螢幕橫向播放

編輯:iOS 相關資訊

需求很常見:App 本身只支援直向(Portrait),但內嵌網頁裡的影片一按全螢幕,就應該自動轉成橫向觀看。做法是透過播放器的通知,動態改變 App 支援的方向。

一、在 AppDelegate 提供動態方向判斷

這個方法由系統在需要決定方向時主動呼叫,不必擔心呼叫時機:

// 為影片旋轉做準備
- (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 來達到同樣效果。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved