Search code examples
swiftavfoundationavplayeravplayerlayer

Put buttons over PlayerLayer - Swift - Programmatically


I have a UIView which Is supposed to play a video using AVPlayerLayer and AVPlayer. I set the player in this way:

fileprivate func setUpPlayer(){
 
            let urlPathString = Bundle.main.path(forResource: "dance", ofType: "mp4")

            if let videoURL = urlPathString{

                let url = URL(fileURLWithPath: videoURL)
                player = AVPlayer(url: url)
                playerLayer = AVPlayerLayer(player: player)

               
                playerLayer.videoGravity = .resizeAspectFill
                
                self.playerView.layer.addSublayer(playerLayer)
                
                
                self.playerView.layer.masksToBounds = true
           
    }
}

override func layoutSubviews() {
    self.layer.cornerRadius = 15
    playerLayer.frame = self.bounds
    self.setupShadow(opacity: 0.6, radius: 6, offset: CGSize.init(width: 0, height: 0), color: .darkGray)
}

The problem is that no matter how many subviews I set over the PlayerView, the video actually goes over everything hiding all the subviews I set before.

Do you know how I can put buttons or actually other UIViews over AVPlayerLayer without it actually hiding them?


Solution

  • Change

    self.playerView.layer.addSublayer(playerLayer)
    

    to

    self.playerView.layer.insertSublayer(playerLayer, at: 0)