我遇到了一个奇怪的问题,在下面的代码中,如果我将playerLayer.frame设置为view.frame,它仍然会加载视频,只是显然它溢出到playerContainer之外。
但是如果我将playerLayer.frame设置为playerContainer.frame,这是有道理的,因为我正在将subLayer添加到playerContainer中,它根本不会呈现。
var player: AVPlayer?
var playerLayer: AVPlayerLayer?
let playerContainer: UIView = {
let view = UIView()
return view
}()
let randomizeButton: UIButton = {
let button = UIButton()
button.setTitle("Change video", for: .normal)
button.backgroundColor = UIColor.black
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
setupVideoPlayer()
setupRandomizeButton()
}
private func setupVideoPlayer() {
view.addSubviewUsingAutoLayout(playerContainer)
playerContainer.topAnchor.constrain(to: view.topAnchor)
playerContainer.leadingAnchor.constrain(to: view.leadingAnchor)
playerContainer.trailingAnchor.constrain(to: view.trailingAnchor)
playerContainer.heightAnchor.constrain(to: view.frame.width)
playerContainer.backgroundColor = UIColor.gray
if let url = URL(string: videoURLArray[0]) {
player = AVPlayer(url: url)
}
playerLayer = AVPlayerLayer(player: player)
//playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
playerLayer?.frame = view.frame
playerContainer.layer.addSublayer(playerLayer!)
player?.play()
}