如何在collectionView中一次播放一个视频?

时间:2019-08-28 17:18:15

标签: ios swift collectionview

我正在构建一个类似于TikTok的应用程序,其中的主要提要是一个UICollectionView,每个单元格中都有一个视频。我的问题是多个视频将同时播放,并且我只希望一次播放一个视频,这取决于该单元是否在视野中。如果单元格不在视野中,我也希望视频暂停。

每个单元格占据整个屏幕,并且collectionView启用了分页。

如果您曾经使用过Instagram或TikTok,我希望功能相同。视频仅在单元格进入视图时播放,而视频在单元格离开视图时暂停。让我知道是否需要更多代码或信息,谢谢!

这是FeedController中的相关代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FeedCell
    cell.delegate = self

    cell.post = posts[indexPath.row]

    if let videoUrl = posts[indexPath.row].videoUrl { 
      player = AVPlayer(url: videoUrl)
      playerLayer = AVPlayerLayer(player: player)

      playerLayer?.zPosition = -1
      playerLayer?.frame = cell.contentView.frame
      playerLayer?.videoGravity = .resizeAspectFill
      cell.contentView.layer.addSublayer(playerLayer!)
      player?.play()

      cell.playerLayer = playerLayer
      cell.player = player
    }

    return cell
}

以下是FeedCell的相关代码:

class FeedCell: UICollectionViewCell {

  var post: Post?

  var playerLayer: AVPlayerLayer?
  var player: AVPlayer?

  override func prepareForReuse() {
      super.prepareForReuse()
      playerLayer?.removeFromSuperlayer()
      player?.pause()
  }

}

1 个答案:

答案 0 :(得分:1)

您可以使用collectionView(:willDisplay:forItemAt:) collectionView( :didEndDisplaying:forItemAt:)委托方法轻松实现这一目标。

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    (cell as? FeedCell).player?.play()
}

func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    (cell as? FeedCell).player?.pause()
}

注意:仅当您的单元格完全从屏幕上消失后,才会调用didEndDisplaying。