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

前端 未结 13 853
小蘑菇
小蘑菇 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:48

    For those of you who are only concerned with resizing the AVPlayer during device rotation, you can alter your layer frame in the viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) method as shown below.

    //Swift 4
    //Method in UIViewController
    //Variable definitions are:
    //self.layer is the AVPlayerLayer
    //self.videoPlayerView is the view that the AVPlayerLayer is the sublayer of
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { context in
            self.layer.layoutIfNeeded()
            UIView.animate(
                withDuration: context.transitionDuration,
                animations: {
                    self.layer.frame = self.videoPlayerView.bounds
                }
            )
        }, completion: nil)
    }
    

    This will animate your layer frame along with all the other views during the rotation.

提交回复
热议问题