我尝试使用AutoLayout设置我在视图中显示的视频的大小/帧。但我无法弄清楚如何正确地做到这一点。这是我的观点的代码:
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不会像我最初想的那样更新值。
如果我使用playerLayer.frame
手动设置CGRect
的大小,一切正常。但我想使用AutoLayout。
那么如何使用AutoLayout设置AvPlayerLayer
的大小?
答案 0 :(得分:7)
执行:
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
}
}