我正在尝试构建一个 UICollectionView,其中每个单元格都包含一个带有不同视频的 MPMoviePlayerController。我希望用户能够就地播放每个视频。
我知道您不能播放 MPMoviePlayerController 的多个实例。关于 Apple 文档的模糊之处在于您是否可以实例化它们并将它们放置在视图中——按照我的阅读方式,您实际上可以做到这一点。然而,我无法让它发挥作用,所以我最终放弃并尝试了一种不同的技术。
相反,我尝试使用选择事件在集合单元格中实例化、放置和自动播放视频。作为一个控件,我在同一个 UIViewController 中的集合视图之外放置了一个附加视图。当我运行它时,外部视图加载得很好 - 视频实例化并且第一帧出现了。并且集合视图中的所有单元格也正确显示。但是,当我选择其中一个集合单元格时,外部视图中的视频完全消失了,而集合视图中的视频实例化但未能出现。我知道它已实例化,因为我对每个视图的背景进行了颜色编码,并且在选择单元格时,视频的背景出现了,但实际视频没有。非常混乱。
所以我想知道您是否甚至可以将视频放在集合视图中?
这是视图控制器的代码:
#import "testViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "tvCollectionCell.h"
@interface testViewController ()
@property (strong) IBOutlet UIView *containerView;
@property (strong) MPMoviePlayerController *videoPlayer;
@end
@implementation testViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated {
self.videoPlayer = [[MPMoviePlayerController alloc]
initWithContentURL: [NSURL fileURLWithPath:
[[NSBundle mainBundle]
pathForResource:@"testvideo" ofType:@"mp4"]]];
CGRect videoFrame = CGRectMake(0, 0, self.containerView.frame.size.width, self.containerView.frame.size.height);
[[self.videoPlayer view] setFrame:videoFrame];
self.videoPlayer.shouldAutoplay = FALSE;
self.videoPlayer.repeatMode = TRUE;
[self.videoPlayer prepareToPlay];
[self.videoPlayer view].backgroundColor = [UIColor orangeColor];
[self.containerView addSubview:[self.videoPlayer view]];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 10;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
tvCollectionCell *tvCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"tvCell" forIndexPath:indexPath];
tvCell.backgroundColor = [UIColor purpleColor];
return tvCell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
tvCollectionCell *tvCell = (tvCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
MPMoviePlayerController *movie = [[MPMoviePlayerController alloc]
initWithContentURL: [NSURL fileURLWithPath:
[[NSBundle mainBundle]
pathForResource:@"testvideo" ofType:@"mp4"]]];
CGRect videoFrame = CGRectMake(0, 0, tvCell.frame.size.width, tvCell.frame.size.height);
[[movie view] setFrame:videoFrame];
movie.shouldAutoplay = TRUE;
movie.repeatMode = TRUE;
[movie prepareToPlay];
[movie view].backgroundColor = [UIColor blueColor];
[tvCell addSubview:[movie view]];
}
@end
谢谢您的帮助!