iOS WKWebView网页播放视频时自动旋转

最近做项目用到了WKWebView,发现在网页上播放视频会调用系统的播放器,但是播放时不能够自动旋转,最后查阅相关资料,终于解决了。附上相关demo:GKWKWebViewDemo

下面简单介绍一下解决步骤:

  1. 首先在AppDelegate里定义一个属性allowRotate,用于控制window是否支持旋转
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return self.allowRotate ? UIInterfaceOrientationMaskAllButUpsideDown : UIInterfaceOrientationMaskPortrait;
}

2.创建UINavigationController的分类,并增加转屏相关方法

// 是否支持自动转屏
- (BOOL)shouldAutorotate
{
    return [self.visibleViewController shouldAutorotate];
}

// 支持哪些屏幕方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return [self.visibleViewController supportedInterfaceOrientations];
}

// 默认的屏幕方向(当前ViewController必须是通过模态出来的UIViewController(模态带导航的无效)方式展现出来的,才会调用这个方法)
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return [self.visibleViewController preferredInterfaceOrientationForPresentation];
}

3.在需要播放视频的控制器里监听window的出现和隐藏,设置allowRotate的对应值

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowVisible:) name:UIWindowDidBecomeVisibleNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowHidden:) name:UIWindowDidBecomeHiddenNotification object:nil];

- (void)windowVisible:(NSNotification *)notify
{
    self.appDelegate.allowRotate = NO;
}

- (void)windowHidden:(NSNotification *)notify
{
    self.appDelegate.allowRotate = YES;
}

这里要注意一点:当播放器开始播放视频,然后用户切换到横屏,点击左上角的Done按钮,会出现播放器消失,控制器还是横屏的bug,解决办法也很简单,只需要在当前控制器里增加以下代码即可:

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

这里写的与demo中的内容有些出入,具体以demo中的为准,下面是demo中的相关截图:

![ ![ ![Simulator Screen Shot 2017年4月21日 下午6.39.30.png](http://upload-images.jianshu.io/upload_images/1598505-d9ec007953c036ce.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ](http://upload-images.jianshu.io/upload_images/1598505-5c9983847abdc13e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ](http://upload-images.jianshu.io/upload_images/1598505-e3d862409d173455.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 15,359评论 4 61
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 179,058评论 25 709
  • 我又要回到老地方 度过旧日的时光 同样的落地窗 照常守候朝阳 我是为自己的着装 还是最初的梦想 默默惆怅 当年那群...
    朱六子阅读 234评论 0 1
  • 食物,总是能带给人慰藉。有人曾说过,没有什么事情比吃饱更重要了。哪怕面临再大的困难,只要吃一顿好饭,就能把心情从低...
    15廖淑君阅读 279评论 1 0
  • 最近在设计Android程序时,因为需要在ScrollView中添加一个ListView列表来显示一些信息。刚开始...
    Boson_Fang阅读 728评论 0 0

友情链接更多精彩内容