iOS 全局禁止橫屏,但視頻播放界面選擇性橫屏的解決辦法

i2414834 8年前發布 | 49K 次閱讀 iOS開發 移動開發

有時我們的APP并沒有適配橫屏的需求,但是在個別視頻播放界面,我們需要在播放視頻的時候橫屏,退出全屏的時候不能橫屏,但是有時候并沒有原生API并沒有給出解決方案。

當其他界面不支持橫屏時:

這個解決方法比較容易

在 APPDelegate.h 文件中增加屬性:是否支持橫屏

/***  是否允許橫屏的標記 */
@property (nonatomic,assign)BOOL allowRotation;

在 APPDelegate.m 文件中增加方法,控制全部不支持橫屏

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.allowRotation) {
        return  UIInterfaceOrientationMaskAllButUpsideDown;
    }
    return UIInterfaceOrientationMaskPortrait;
}

這樣在其他界面想要橫屏的時候,我們只要控制 allowRotation 這個屬性就可以控制其他界面進行橫屏了。

//需在上面#import "AppDelegate.h"
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = YES;
//不讓橫屏的時候 appDelegate.allowRotation = NO;即可

播放界面橫屏

所以這里可以使用 UIWindow 的通知,就可以解決

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(begainFullScreen) name:UIWindowDidBecomeVisibleNotification object:nil];//進入全屏
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];//退出全屏

在退出全屏時,增加邏輯讓其強制編程豎屏,這樣當全屏播放的時候,點擊 down("完成") 時,就會自動變成豎屏了。

// 進入全屏
-(void)begainFullScreen
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
}
// 退出全屏
-(void)endFullScreen
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = 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];
    }
}

上面的兩個方案已經足夠解決只有部分界面需要支持橫屏的問題了,親測可用

 

來自:http://www.jianshu.com/p/73e077400e82

 

 本文由用戶 i2414834 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!