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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With