Draw button on top of AVPlayer

前端 未结 5 2079
执念已碎
执念已碎 2020-12-28 09:29

I have to draw a label or button on top of video relay next previous , leave comment . List of video have it, once user select one item from the table,it need t

5条回答
  •  悲&欢浪女
    2020-12-28 10:19

    You're using an AVPlayerViewController, so there's no reason to access your application's window like in Alessandro Ornano's answer. Why reinvent the wheel? Every AVPlayerViewController has a contentOverlayView property which allows you to place views between the player and the controls.

    First, create a new AVPlayerItem and listen for the AVPlayerItemDidPlayToEndTimeNotification notification on that item. Load the item into your player and begin playback.

    Once the item completes, the selector your specified to listen for the AVPlayerItemDidPlayToEndTimeNotification notification will be called. In that selector, access the contentOverlayView directly and add your buttons:

    In some view controller or other object:

    let playerVC = AVPlayerViewController()
    
    // ...
    
    func setupPlayer {
    
        let playerItem = AVPlayerItem(...)
        playerVC.player?.replaceCurrentItemWithPlayerItem(playerItem)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(VC.itemFinished), name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)
        self.presentViewController(playerVC, animated: true) { 
            self.playerVC.player?.play()
        }
    }
    
    func itemFinished() {
        let btn = UIButton(type: .System)
        btn.addTarget(self, action: #selector(VC.buttonTapped), forControlEvents: .TouchUpInside)
        self.playerVC.contentOverlayView?.addSubview(btn)
    }
    
    func buttonTapped() {
        print("button was tapped")
        // replay/comment logic here
    }
    

    As stated in the comments (and a rejected edit), buttons may not work in the contentOverlayView. For an alternate solution, see Pyro's answer.

    You could also subclass AVPlayerViewController and do everything inside an instance of your subclass, but Apple warns against that:

    Do not subclass AVPlayerViewController. Overriding this class’s methods is unsupported and results in undefined behavior.

提交回复
热议问题