我正在尝试研究如何在 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
}
}
我使用以下代码在 -cellForRowAtIndexPath:
中设置了 player
:
let videoPlayer = AVPlayer(playerItem: AVPlayerItem(asset: cellVideo))
cell.playerView.player = videoPlayer
这工作正常,但是,当单元格不在 View 中时,我不想播放视频。我应该将 player
设置为 nil,然后在单元格再次显示时再次设置 player
,还是应该暂停视频?或者我应该使用另一种方式吗?
最佳答案
编辑
是的,您应该将播放器设置为 nil 以提高性能。 我认为您还应该通过重写 prepare for reuse 方法在自定义单元类中将播放器设置为 nil。
override func prepareForReuse() {
player = nil
super.prepareForReuse()
}
此外,如果您的目标是模仿新闻源行为,我建议您查看 AVPlayer:PrerollAtRate它让您在特定时间竖起大拇指。
您可以使用委托(delegate)方法来暂停和恢复播放器。 只需确保将 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()
}
}
关于ios - 如何在 UITableViewCell 中处理 AVPlayer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40870916/