将 ViewController 作为 Overlay 嵌入到 AVPlayerController 中

Embed a ViewController into a AVPlayerController as an Overlay

我的问题:我正在尝试将 ViewController(带有图像和按钮)嵌入到 AVPlayerController 中,类似于 YouTube 的显示方式在他们的视频上投放广告(在视频底部,并将保留在那里)。

我的做法: 我有以下测试代码

let AVPC = AVPlayerViewController()
            avpc!.player = self.contentPlayer
            avpc!.view.frame = f
            self.addChild(avpc!)
let adView = UIView()
adView.frame = CGRect(x: ??, y: ??, width: 300, height: 70)
AVPC.contentOverlayView.addSubview(adView)

结果:我的视图在最小化时会正确计算我的 AVPlayerController 的大小。但是,当我进入全屏视图时,它要么越界要么根本不起作用。

模拟

你应该看看 autolayout, and there are some tools for auto layout with less code, like SnapKit

这是一个不用任何库处理它的示例方法。

class ViewController: UIViewController {

    let adView: UIView = {
        let view = UIView()
        view.backgroundColor = .red
        return view
    }()

    func playVideo() {
        let videoURL = URL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
        let player = AVPlayer(url: videoURL!)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        playerViewController.contentOverlayView?.addSubview(adView)

        adView.translatesAutoresizingMaskIntoConstraints = false
        adView.heightAnchor.constraint(equalToConstant: 100).isActive = true
        adView.bottomAnchor.constraint(equalTo: adView.superview!.bottomAnchor, constant: -20).isActive = true
        adView.leadingAnchor.constraint(equalTo: adView.superview!.leadingAnchor, constant: 40).isActive = true
        adView.trailingAnchor.constraint(equalTo: adView.superview!.trailingAnchor, constant: -40).isActive = true

        self.present(playerViewController, animated: true) {
            playerViewController.player!.play()
        }
    }
}