SriKanth SriKanth - 2 years ago 281
Objective-C Question

How to stop video playing in YTPlayerView inside UICollectionViewCell when scrolled?

I am using

(Horizontal scroll) with one item visible at a time on the screen. I have added a
inside custom cell and changed the class name to
in Identity inspector.

I have enabled AutoPlay and it is playing well. But, when I scroll to next or previous item I want to stop the player. I tried stopping the player in 'didEndDisplayingCell' by getting custom cell object with
. But
instance with custom cell object returns (null) in 'didEndDisplayingCell'. So I am not able to stop video play. How can I stop video play when scroll to next / prev item?

And I have 3 different custom
cells to display text, images and videos (YTPlayerView or AVPlayer).

I tried to get the custom video cell object in 'cellForItemAtIndexPath' by saving previous visible cell indexpath. And I am able to get the custom cell object, but when I try to get the instance of
it is returning new object for

Can anyone suggest me the right way to handle youtube videos in

Answer Source


Now I've understood the problem, however when I try my self, I get a perfectly valid cell reference in the - (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath delegate.

It shouldn't be null there. You should be getting this each time a cell disappears, where you should check the type of the cell that is hiding!

If the cell is a type of your YouTube cell then only stop the video playback. Here is a rough sample:

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:[YouTubeVideoCell class]]) {
        YouTubeVideoCell *youtubeCell = (YouTubeVideoCell*)cell;
        [youtubeCell stopVideo];

Where YouTubeVideoCell should be your custom YTPlayerView cell subclass and stopVideo should be a public method of the cell where inside it you stop the YTPlayerView video.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download