RickBlog

恩返し

CollectionViewのCellで動画を再生(Twitter風)

やりたいこと

CollectionViewのCellに動画を配置し、スクロールした画面中央あたりの動画のみを再生させたい。(Twitterのようなイメージ)

参考にした記事

swift 画面上に表示されているcollectionviewの中心のcellを取得する - Qiita
iOS - 【iOS,Swift】CollectionViewの画面内に表示されているセルの取得方法|teratail
【Swift3】UITableViewで一番下までスクロールしたことを検知する - Qiita

実装方法について

画面中央あたりの動画のみを再生する

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  print("画面中央より上のcellの動画を止める処理")
  print("画面中央より下のcellの動画を止める処理")
  print("画面中央のcellの動画を再生する処理")

}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let cell = cell else {
            return
        }

        let center = self.view.convert(collectionView.center, to: collectionView)
        guard let index = collectionView.indexPathForItem(at: center) else { 
            return 
        }
        
        if let beforCell = collectionView.cellForItem(at: [0,index.row - 1]) {
            beforCell.pause()
        }
        
        if let afterCell = collectionView.cellForItem(at: [0,index.row + 1]) {
            afterCell.pause()
        }
        
        if let centerCell = collectionView.cellForItem(at: index) {
            centerCell.play()
        }

}

画面の一番下にスクロールしたときの処理

func scrollViewDidScroll(_ scrollView: UIScrollView) {
  if collectionView.contentOffset.y + collectionView.frame.size.height > collectionView.contentSize.height && collectionView.isDragging {
    print("画面中央より上のcellの動画を止める処理")
    print("画面中央のcellの動画を再生する処理")
  }
}

画面の一番上にスクロールしたときの処理

func scrollViewDidScroll(_ scrollView: UIScrollView) {
  if videoCollectionView.contentOffset.y < 0 && videoCollectionView.isDragging {
    print("画面中央より下のcellの動画を止める処理")
    print("画面中央のcellの動画を再生する処理")
  }
}

画面の最上部をタップし、画面が1番上に戻ったときの処理

func scrollViewDidScroll(_ scrollView: UIScrollView) {
  if videoCollectionView.contentOffset.y == 0 {
    print("画面中央より下のcellの動画を止める処理")
    print("画面中央のcellの動画を再生する処理")
  }
}