我正在收藏视图中的AVPlayer中加载视频,但它会重复一些单元数据

时间:2019-05-29 09:32:39

标签: swift

我正在将AVPlayer中的视频加载到收藏夹视图中。一些单元格重复数据。如何解决此问题?

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell:homecollCell = self.collectionview.dequeueReusableCell(withReuseIdentifier: "homecollCell", for: indexPath) as! homecollCell
    //cell.player?.pause()

    let obj = self.friends_array[indexPath.row] as! Home

    cell.img.sd_setImage(with: URL(string:self.appDelegate.imgbaseUrl!+obj.thum), placeholderImage: UIImage(named: ""))

    let url = URL.init(string: self.appDelegate.imgbaseUrl!+obj.video_url)

    let screenSize: CGRect = UIScreen.main.bounds
    cell.playerItem = AVPlayerItem(url: url!)
    //cell.player!.replaceCurrentItem(with: cell.playerItem)
    cell.player = AVPlayer(playerItem: cell.playerItem!)
    cell.playerLayer = AVPlayerLayer(player: cell.player!)
    cell.playerLayer!.frame = CGRect(x:0,y:0,width:screenSize.width,height: screenSize.height)
    cell.playerLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cell.playerView.layer.addSublayer(cell.playerLayer!)

    cell.player?.play()

2 个答案:

答案 0 :(得分:2)

单元格是可重用的,因此您必须使用prepareForReuse()删除或放弃对其他单元格所做的更改。就是这样在cell内部调用它。

override func prepareForReuse() {
     super.prepareForReuse()
     self.label.text = nil
}

答案 1 :(得分:0)

移动AVPlayerLayer并在单元格的类中初始化图层。 homecollCell

在您的班级中覆盖prepareForReuse()Docs

prepareForReuse内,停止播放器并使用AVPlayerLayer Docs

删除添加的removeFromSuperlayer