UICollectionView中的视频:滚动问题

时间:2016-06-19 08:52:02

标签: ios uicollectionview avplayerviewcontroller

我在UICollectionView中显示了一些视频;当应用程序加载时,它运行正常,而当用户滚动UICollectionView时,视频没有加载,所有单元格都是灰色的,永远不会填充正确的视频,即使在调试中我看到正确的mp4网址。

以下是代码:

    func collectionView(cv: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let videoCell = collectionView!.dequeueReusableCellWithReuseIdentifier("VideoCell", forIndexPath: indexPath) as? UICollectionViewCell

        var aPlayer = AVPlayer()
        let moviePlayerController = AVPlayerViewController()

        let item = self.wall[indexPath.row]

        print("URL:"+item.video_link)

        let fileUrl = NSURL(string: item.video_link)

        dispatch_async(dispatch_get_main_queue(), {
        aPlayer = AVPlayer(URL: fileUrl!)

        moviePlayerController.player = aPlayer
        moviePlayerController.view.frame = CGRectMake(0, 0, videoCell!.frame.size.width, videoCell!.frame.size.height)
        moviePlayerController.videoGravity = AVLayerVideoGravityResizeAspectFill
        moviePlayerController.view.sizeToFit()
        moviePlayerController.player?.actionAtItemEnd=AVPlayerActionAtItemEnd.None
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: "playerItemDidReachEnd:",
                                                         name: AVPlayerItemDidPlayToEndTimeNotification,
                                                         object: moviePlayerController.player!.currentItem)
        moviePlayerController.showsPlaybackControls = false
        moviePlayerController.player?.play()
        /*
        videoCell?.layer.shouldRasterize = true;
        videoCell!.layer.rasterizationScale = UIScreen.mainScreen().scale;
        */
        videoCell!.addSubview(moviePlayerController.view)
        })
        return videoCell!
    }

任何人都可以帮我理解这个问题吗?

1 个答案:

答案 0 :(得分:2)

  1. 您应该将子视图添加到videoCell!.contentView而不是videoCell本身。

  2. 您在一个单元格中添加了大量moviePlayerController.view个!无论何时要显示一个单元格,都会调用cellForItemAtIndexPath,但这并不意味着在出列后你会有一个干净的单元格,它可能会出现在屏幕上不再显示的先前单元格上。有Bool或检查videoCell!.subviews.count以确定您之前是否添加了moviePlayerController.view。如果您已经添加了该网址,请更改网址(如果可能)或将其删除,然后重新添加。

  3. p.s:最好的方法是定义一个自定义UICollectionViewCell类。