[英]How to handle AVPlayer in a UITableViewCell?
我正在尝试研究如何在UITableViewCell
成功使用AVPlayer
。 在我的UITableViewCell
里面,我有一个UIView
子类,里面有一个AVPlayerLayer
,使用这个代码(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
}
}
我使用以下代码将player
设置为-cellForRowAtIndexPath:
:
let videoPlayer = AVPlayer(playerItem: AVPlayerItem(asset: cellVideo))
cell.playerView.player = videoPlayer
这很好,但是,当单元格不在视图中时,我不希望视频播放。 我应该将player
设置为nil,然后当单元格显示再次设置player
时,还是应该暂停视频? 或者我应该使用另一种方式吗?
您可以实现此UITableViewDelegate方法,以便在单元格不在视图中时执行所需操作:
optional func tableView(_ tableView: UITableView,
didEndDisplaying cell: UITableViewCell,
forRowAt indexPath: IndexPath) {
}
我个人会停止视频并将播放器设置为nil,因为当单元格变为可见时,会调用cellForRowAt indexPath
。
编辑
是的,您应该将播放器设置为nil以提高性能。 我认为您还应该通过覆盖准备重用方法将播放器设置为自定义单元类中的nil。
override func prepareForReuse() {
player = nil
super.prepareForReuse()
}
此外,如果您的目标是模仿新闻源行为,我建议您查看AVPlayer:PrerollAtRate它让您在特定时间显示拇指。
您可以使用委托方法暂停和恢复播放器。 只需确保将UITableViewCell转换为自定义类
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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.