AVPlayer layer inside a view does not resize when UIView frame changes

前端 未结 13 870
小蘑菇
小蘑菇 2020-12-23 17:08

I have a UIView which contains an AVPlayer to show a video. When changing orientation, I need to change the size and location of the video.

<
13条回答
  •  暖寄归人
    2020-12-23 17:41

    Converting @Suran's solution to Swift:

    First, create a class inheriting UIView where you override only 1 variable:

    import UIKit
    import AVFoundation
    
    class AVPlayerView: UIView {
        override class var layerClass: AnyClass {
            return AVPlayerLayer.self
        }
    }
    

    Then add a simple UIView using the interface builder and change its class to the one you just created: AVPlayerView

    Then, make an outlet for that view. Call it avPlayerView

    @IBOutlet weak var avPlayerView: AVPlayerView!
    

    Now, you can use that view inside your viewcontroller and access its avlayer like this:

    let avPlayer = AVPlayer(url: video)
    let castedLayer = avPlayerView.layer as! AVPlayerLayer
    castedLayer.player = avPlayer
    avPlayer.play()
    

    The layer will now follow the constraints just like a regular layer would do. No need to manually change bounds or sizes.

提交回复
热议问题