AVP图层视图控制器自动旋转关闭



我正在以纵向模式开发iOS应用程序,并且工作正常。

问题是我在导航控制器上方呈现AVPlayerViewController(两者都以编程方式创建(。这个播放器支持所有的旋转(我不知道为什么!

我想将其修复为纵向模式,就像应用程序的其他部分一样。

我们该怎么做呢?

创建继承自 AVPlayerViewController 的新类,并像这样实现支持的接口方法。在此之后,不要初始化AVPlayerViewController的对象,只需创建您创建的类的对象即可。

class MyPortraitVideoController: AVPlayerViewController {

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}


编辑添加

请注意,AVPlayerViewController的文档指出:

重要不要

子类 AVPlayerViewController。覆盖这一点 类的方法不受支持,并导致未定义的行为。

由于这是公认的答案,我假设 OP 已经尝试过并且它有效,但我想我应该在这里添加一条注释,以确保未来的读者意识到任何潜在的问题。 未定义的行为意味着这可能会在未来的 iOS 版本中停止工作。

就我而言,我不得不限制某些视图的横向。所以我在AppDelegate中将支持的InterfaceOrientationsFor设置为纵向。当我演示AVPlayerViewController时,我必须将支持的InterfaceOrientationsFor设置为AppDelegate中的所有内容。还要检查以下代码。

应用委托.swift

var shouldSupportLandscape = Bool()
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
     if self.shouldSupportLandscape == true {
          return .all
      }else {
          return .portrait
      }   
 }

当存在AVPlayerView控制器时

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.shouldSupportLandscape = true

关闭 AVPlayerViewController 时

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.shouldSupportLandscape = false

最新更新