UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to reuse AVPlayerViewController inside of a UIScrollView with paging enabled

Forums > iOS

Hi there,

I'm attempting to implement an Instagram-like gallery using a UICollectionView that houses a UIScrollView with paging enabled. During a configure method call, I iterate over an array of Media objects that are added to the UIScrollView's subview using an offset.

I'm having trouble, in particular, using AVPlayerViewController to show multiple videos in a single UIScrollView. Below is my particular case for the "video" part of my configure method.

let xPosition = scrollView.bounds.width * CGFloat(i)

...

case "video":
        print("Configuring media with the following video url: \(media[i].url)")
        guard let url = URL(string: media[i].url) else {
            print("Unable to create URL from string!")
            return
        }

        let player = AVPlayer(url: url)
        playerController.player = player
        playerController.view.frame = CGRect(x: xPosition, y: 0, width: scrollView.bounds.width, height: scrollView.bounds.height)
        playerController.videoGravity = .resizeAspect
        playerController.showsPlaybackControls = true
        playerController.view.backgroundColor = .white
        scrollView.addSubview(playerController.view)
...

One thing to note is that playerController is a class property of type AVPlayerViewController that I'm attempting to reuse. I believe what is happening here, is that every iteration of the for loop is causing the single playerController's frame to get pushed further and further left as more media items are iterated over. Because of this, I don't know if there's a particular way to reuse the same AVPlayerViewController, or if I need to use one for each video.

I prefer to use AVPlayerViewController for its "out-of-the-box" readiness regarding controls, etc.

Thanks!

3      

I ended up solving this by initially setting the frame on the first pass of the for-loop, and then adjusting the frame using UIScrollView's scrollViewWillBeginDecelerating method.

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.