我正在尝试在UIView中播放视频,但视频播放器总是出现在UIView之外,我将AVPlayerViewController嵌入其中。
以下是我到目前为止所做的......
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()
}
...
}
UIView的背景颜色设置为白色。从截图中可以看出,AVPlayer不在UIView中。
我尝试手动设置AVPlayer的尺寸和位置,但也没有运气。
我正在使用Xcode 9.2。该项目没有关于任何布局问题的警告。
如何完美地对齐AVPlayer,以便显示在UIView内。
由于
答案 0 :(得分:14)
更改此行:
smallVideoPlayerViewController.view.frame = videoView.frame
到此:
smallVideoPlayerViewController.view.frame = videoView.bounds
原因是因为videoView.frame在其超级视图中包含了您不想要的原点。 videoView.bounds只是原点为0,0的大小。
当然你可能想进一步设置自动调整大小的掩码,以保持视频播放器框架像这样:
smallVideoPlayerViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
甚至要完全自动布局。