Here is another approach, purists won't like it, but I couldn't find out how to properly free/re-init the YTPlayerView created in my custom UICollectionViewCell.
Considering you will only play one video at time, because two several instances of YTPlayer won't play simultaneously, you just have to hide reused cells with video's thumbnail. Simply put an UIImageView above the YTplayerView in your sublclass of UICollectionViewCell xib, and set the thumbnail in it:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//... load customcell xib, manage cellId etc.
// set video id that will be read by the custom cell
[cell setVideoId:cellVideoId];
// set above UIImage
NSData * thumbnailData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: videoThumbnailURL]];
UIImage * videoThumbnail = [UIImage imageWithData: thumbnailData];
[cell.thumbnailImage setImage:videoThumbnail];
return cell;
}
There, in custom UICollectionViewCell .m file you just need to implement a button that launch the video when clicked ...
- (IBAction)clickPlay:(id)sender {
if (videoId != nil){
[ccellYTPlayerView loadWithVideoId:videoId playerVars:playerVars];
// Hide thumbnail image to reveal the YTPlayerView
[thumbnailImage setHidden:true];
}
}
... and configure reusability of this custom cell, which works flawlessly for native obvjects :
-(void) prepareForReuse{
[super prepareForReuse];
// preparing UIImage to host another thumbnail
thumbnailImage.image = nil;
[thumbnailImage setHidden:false];
}
This way, YTplayers can appear in other cells, no one will see it because hidden by the thumbnail, and the sound produced is not a problem because user will assume that it comes from the original cell (which is not on screen anymore because of scrolling).
I know that's not really clean, but it helped me so far, YTPlayer instance is not so easy to recycle.