Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding an AVPlayerViewController into a UIView

I am trying to play a video inside a UIView, but the video player always appears outside of the UIView which I am embedding the AVPlayerViewController into.

Below is what I have so far....

class ViewController: UIViewController {

    let smallVideoPlayerViewController = AVPlayerViewController()

    @IBOutlet weak var videoView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let myFileManager = FileManager.default
        let mainBundle = Bundle.main
        let resourcesPath = mainBundle.resourcePath!

        guard let allItemsInTheBundle = try? myFileManager.contentsOfDirectory(atPath: resourcesPath) else {
            return
        }

       let videoName = "test"

       let videoPath = Bundle.main.path(forResource: videoName, ofType: "mp4")
       let videoUrl = URL(fileURLWithPath: videoPath!)

       smallVideoPlayerViewController.showsPlaybackControls = false
       smallVideoPlayerViewController.player = AVPlayer(url: videoUrl)

       videoView.addSubview(smallVideoPlayerViewController.view)

       smallVideoPlayerViewController.view.frame = videoView.frame

       smallVideoPlayerViewController.player?.play()
    }
 ...
}

The background colour of UIView is set to white. As seen from the screenshot, AVPlayer is outside of the UIView.

Output of the code above

I tried manually setting the dimensions and position of the AVPlayer, but no luck with that either.

I am using Xcode 9.2. The project has not warnings regarding to any layout issues.

How can I perfectly align the AVPlayer, so that is would appear inside the UIView.

Thanks

like image 948
fnisi Avatar asked Jan 01 '18 10:01

fnisi


1 Answers

Change this line:

smallVideoPlayerViewController.view.frame = videoView.frame

to this:

smallVideoPlayerViewController.view.frame = videoView.bounds

The reason is because videoView.frame includes the origin in its superview which you don't want. videoView.bounds is just the size with an origin of 0,0.

Of course you might want to go further set the auto-resizing mask to keep the video player frame the same like this:

smallVideoPlayerViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

or even to go full blown auto-layout.

like image 145
Upholder Of Truth Avatar answered Nov 12 '22 14:11

Upholder Of Truth