简体   繁体   中英

How to make AVPlayer & AVPlayerLayer scrollable (AVFoundation)

I am using a collectionView to display both images/videos.

I am retrieving the content from Firebase.

With the images, I can scroll. I added a scrollview and manually added 20 imageViews as Firebase do not allow bulk retrieval of images/content. And then check if a value exists, and if so, display the content at a certain index (of image 1-20).

I did seem to notice when define a certain number in this piece of code:

  func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1

    }

I can scroll the videos. However since I cannot retrieve multiple images, I resorted to the more inconvenient manner or adding 20 imageViews. To display videos, I am doing the following:

   if let firstVidURLString = post?.firstVideoURL, let firstVideoURL = URL(string: firstVidURLString) {
            self.volumeView.isHidden = false
            videoPlayer = AVPlayer(url: firstVideoURL)
            videoPlayerLayer = AVPlayerLayer(player: videoPlayer)
            videoPlayerLayer?.frame = self.firstImageView.frame
            videoPlayerLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
            layoutIfNeeded()
            videoPlayerLayer?.zPosition = 0
            self.contentView.layer.addSublayer(videoPlayerLayer!)
            self.volumeView.layer.zPosition = 1
            videoPlayer?.play()
            videoPlayer?.isMuted = isMuted
        }

I am happy with how it is placed, I have defined the frame/bounds in correlation to the first image view I have. Surely, that should help me scroll? As it takes up the same size as one image view. Alas, the video player/video layer is just static and will not conform to the scrollview. Any ideas on how I can tackle this?

Thank you.

Figured it out. This is for anyone else, in the future.

Connect your scrollView, if you have one, to the corresponding .swift file ie ViewController, CollectionViewCell etc.

Once you do that, simply add this line.

self.[your scrollview].layer.addSublayer(the name of the video layer !)

And you'll be fine!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM