我正在尝试在以前加载的子视图下面添加函数setupPlayerView
的子图层。子视图的加载速度比图层快,因为创建图层的函数使用的字符串是从另一个类UIViewController
修改的(我想加载单个视频)。我在stackoverflow上找到了答案,但.insertSublayer(playerLayer, below: self.controlsContainerView.layer)
的建议解决方案对我不起作用。如何确保视频图层依次位于我的所有其他子视图(如controlsContainerView
及其子视图(例如activityIndicatorView
)下?
这就是我现在所得到的:
class PlayerView: UIView {
var urlString: String? {
didSet {
setupPlayerView()
}
}
override init(frame: CGRect){
super.init(frame: frame)
//although the function is called immediately it is not the "lower" than everything else
setupPlayerView()
//add subview with controls (e.g. spinner)
controlsContainerView.frame = frame
addSubview(controlsContainerView)
//add to subview and center spinner in subview
controlsContainerView.addSubview(activityIndicatorView) // (spinner)
controlsContainerView.addSubview(whiteView)
//...
}
//... irrelevant code (closures like `activityIndicatorView` and `whiteView`)
//setup video player
func setupPlayerView() {
if let urlString = self.urlString, let videoURL = NSURL(string: urlString){
print(urlString)
//player's video
if self.player == nil {
player = AVPlayer(url: videoURL as URL)
}
//add sub-layer
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.frame
self.controlsContainerView.layer.insertSublayer(playerLayer, below: self.controlsContainerView.layer)
//when are frames actually rendered (when is video loaded so one can remove spinner)
player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
}
}
对于那些感兴趣的人:我在另一个类(ViewController)中以下列方式更改urlString
:
videoPlayerView.urlString = videoUrl //videoUrl being some link to a video source