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

How to Play video on visible and pause video invisible collectionview cell?

我想创建一个功能,我想在其中播放或暂停 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 
}