简体   繁体   中英

How to handle AVPlayer in a UITableViewCell?

I'm trying to work out how to successfully use an AVPlayer inside a UITableViewCell . Inside my UITableViewCell I have a UIView subclass that has an AVPlayerLayer inside it using this code (given by Apple):

class PlayerView: UIView {
    var player: AVPlayer? {
        get {
            return playerLayer.player
        }
        set {
            playerLayer.player = newValue
        }
    }

    var playerLayer: AVPlayerLayer {
         return layer as! AVPlayerLayer
    }

    override class var layerClass : AnyClass {
         return AVPlayerLayer.self
    }

}

I set the player in -cellForRowAtIndexPath: using the following code:

let videoPlayer = AVPlayer(playerItem: AVPlayerItem(asset: cellVideo))
cell.playerView.player = videoPlayer

This works fine, however, when the cell is out of view, I don't want the video to play. Should I be setting the player to nil, and then when the cell shows again set the player again, or should I just pause the video? Or is there another way I should be using?

You can implement this UITableViewDelegate method, to do what you want when the cell is out of the view:

optional func tableView(_ tableView: UITableView, 
   didEndDisplaying cell: UITableViewCell, 
           forRowAt indexPath: IndexPath) {

}

I'd personally stop the video and set the player to nil since cellForRowAt indexPath is called when a cell become visible.

EDIT

Yes you should set the player to nil for performance improvements. I think you should also set the player to nil in the custom cell class by overriding the prepare for reuse method.

override func prepareForReuse() {
    player = nil
    super.prepareForReuse()
}

Also if your goal is to mimick a newsfeed behavior, I suggest looking at AVPlayer:PrerollAtRate it let's you show a thumb at a specific time.


You can make use of the delegate methods to pause and resume the player. Just make sure to cast the UITableViewCell to your custom class

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    //cast the cell as your custom cell
    if let myCell = cell as? MyCustomCell
    {
        myCell.player!.play()
    }

}


func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    //cast the cell as your custom cell
    if let myCell = cell as? MyCustomCell
    {
        myCell.player!.pause()
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM