阻止AVPlayer在tableviewcell中播放 [英] Stop AVPlayer from playing in tableviewcell
问题描述
我正在使用AVPlayer
在我的TableViewCell
中显示视频.它正在TableViewCell
中播放,但问题是我无法停止它.
我已使用此代码在cellforRow中播放视频
I'm using AVPlayer
for displaying video in my TableViewCell
. It is playing in TableViewCell
, but the problem is that I'm not able to stop it.
I've used this Code to play video in cellforRow
avPlayer = AVPlayer(url: videoURL! as URL)
playerLayer = AVPlayerLayer(player: avPlayer)
playerLayer.frame = CGRect(x: cell.videoview.frame.origin.x, y: cell.videoview.frame.origin.x, width:cell.videoview.frame.size.width, height: cell.videoview.frame.size.height)
cell.videoview.layer.addSublayer(playerLayer)
avPlayer?.play()
avPlayer
和playerLayer
在viewController
中定义为
var avPlayer : AVPlayer?
var playerLayer = AVPlayerLayer()
我正在使用此代码来停止视频
I'm using this code to stop the video
self.avPlayer?.pause()
self.playerLayer.removeFromSuperlayer()
self.avPlayer?.rate = 0.0
self.avPlayer?.replaceCurrentItem(with: nil)
self.avPlayer = nil
我的问题是,如何才能停止通过AVPlayerLayer
上的AVPlayer
播放视频?
请提出解决方案,如果有其他选择,也请提出解决方案.
My question is this how can I stop the video running through AVPlayer
on AVPlayerLayer
?
Please suggest a solution, if there is any alternative for this please suggest that as well.
推荐答案
Due to the reusable behavior of the cell, it releases the child view instance with itself so you have to stop it in the didEndDisplayingCell
delegate method.
override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? MyCustomCell {
if let play = player {
print("stopped")
play.pause()
player = nil
print("player deallocated")
} else {
print("player was already deallocated")
}
}
}
或
您可以获取单元实例并搜索播放器实例并将其停止.
You can get the cell instance and search the player instance and stop it.
for view in cell.subviews {
//after comparison stop the player here
}
这篇关于阻止AVPlayer在tableviewcell中播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!