如何在可见和暂停视频不可见 collectionview 单元格上播放视频?

问题描述

我想创建一个功能,在其中我想在 colletionview 单元格上播放或暂停视频。 在我的应用程序中,我使用了两个单元格,一个用于视频,另一个用于静态单元格(仅图像) 播放我使用 AVKit 和 AVFoundation 的视频,效果很好。

为了获得完整的可见单元格,我使用 this code

我的问题是 我可以获得可见的单元格编号,但我不知道如何使用该代码在完整的可见单元格上播放并在单元格不可见时暂停视频。

解决方法

您可以使用 scrollViewDidEndDecelerating 委托方法,获取可见单元格并检查这些可见单元格的框架是否在集合视图的边界内,

extension ViewController : UICollectionViewDelegateFlowLayout {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let visibleCells = self.collectionView.visibleCells
        for cell in visibleCells {
            if self.collectionView.bounds.contains(cell.frame) { // condition here should do the trick to find cells which are completely visible in collection view
                cell.playVideo() //probably you can play video here
            }
            else {
                cell.pauseVideo() //you can pause video here
            }
        }
    }
}

最后在你的单元格中实现 prepareForResuse 并暂停视频

override func prepareForReuse() {
    super.prepareForReuse()
    //you can pause your video here
   // not sure which component you are using,if using AVPlayerLayer might reset it or dispose it entirely depends on your usecase 
}