[英]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.