我想在UITableView中显示像Instagram这样的视频,当该单元格完全可见时它将自动播放,而当该单元格不完全可见时将暂停播放。我尝试过:
extension MediaViewController {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.playSingleVideo()
}
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
self.playSingleVideo()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.playSingleVideo()
}
}
private extension MediaViewController {
@objc func appEnteredToBackground() {
self.playSingleVideo(pauseAll: true)
}
@objc func appEnteredFromBackground(_ notification: NSNotification) {
self.playSingleVideo()
}
}
private extension MediaViewController {
func playSingleVideo(pauseAll: Bool = false) {
if let visibleCells = self.Tableview.visibleCells as? [MediaCell], !visibleCells.isEmpty {
if pauseAll {
visibleCells.forEach { $0.playerView?.player?.pause() }
} else {
var maxHeightRequired: Int = 70
var cellToPlay: MediaCell?
visibleCells.reversed().forEach { (cell) in
let cellBounds = self.view.convert(cell.playerView.frame, from: cell.playerView)
let visibleCellHeight = Int(self.view.frame.intersection(cellBounds).height)
if visibleCellHeight >= maxHeightRequired {
maxHeightRequired = visibleCellHeight
cellToPlay = cell
}
}
visibleCells.forEach { (cell) in
if cell === cellToPlay {
cell.playerView?.player?.play()
} else {
cell.playerView?.player?.pause()
}
}
}
}
}
}
但是,加载视图时,前两个单元会同时开始播放,并且只有在滚动时它才能正常工作。有时甚至无法播放视频。