使用 AutoLayout 设置 AVPlayer/AVPlayerLayer 大小?

Set AVPlayer/AVPlayerLayer size using AutoLayout?

我正在尝试使用 AutoLayout 设置我在我的视图中显示的视频的 size/frame。但我无法弄清楚如何正确地做到这一点。这是我的观点的代码:

import UIKit
import AVKit

class VideoMeetingView: UIView {

    lazy var playerLayer: AVPlayerLayer = {
        let layer = AVPlayerLayer()
        return layer
    }()

    private lazy var videoView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .blue
        return view
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
        self.addSubviewsAndConstraints()

        playerLayer.frame = videoView.bounds
        videoView.layer.addSublayer(playerLayer)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func addSubviewsAndConstraints() {
        self.addSubview(videoView)

        videoView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        videoView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        videoView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        videoView.heightAnchor.constraint(equalToConstant: 600).isActive = true
    }

}

如果我打印出 videoView.bounds 的值,它只是 (0, 0, 0, 0),所以我猜 AutoLayout 不会像我最初想的那样更新值。

如果我使用 CGRect 手动设置 playerLayer.frame 的大小,一切正常。但是我想用AutoLayout。

那么如何使用 AutoLayout 设置 AvPlayerLayer 的大小?

做:

self.playerLayer = {
   let layer = AVPlayerLayer(player: self.player)
    layer.videoGravity = .resizeAspect
    layer.needsDisplayOnBoundsChange = true
    return layer
}()

这会导致图层在其父级的边界发生变化时调整纵横比大小。

此外,您可能需要添加:

override func layoutSubviews() {
    super.layoutSubviews()

    self.playerLayer.frame = self.bounds
}

这样无论如何它都有正确的框架..

另一种选择是使 AVPlayerLayer 成为 UIView 本身的实际层,而不是子层:

class VideoView : UIView
{
    override var layer: CALayer {
        return AVPlayerLayer.class
    }
}