微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在可见和暂停视频不可见 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 
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。