显示错误内容的单元格

Cells showing wrong contents

我正在用图像和视频填充单元格。有的有图片,有的有视频。

对于图像,没问题。然而,当显示图片和视频时,事情变得很奇怪。包含视频的单元格将是空白的,但下一个单元格将显示视频,而图像不会出现这种情况。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object{
static NSString *simpleTableIdentifier = @"cell";

self.cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (self.cell == nil) {
    self.cell = [[SearchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}


PFFile *videoFile = [object objectForKey:@"video"];
PFFile *imageFile = [object objectForKey:@"photo"];

if (imageFile != nil) {

    self.cell.movie.view.hidden = YES;
    [self.cell.movie stop];        
    self.cell.photo.hidden = NO;
    self.cell.photo.file = imageFile;
    [self.cell.photo loadInBackground];
}

else {
       dispatch_async(dispatch_get_main_queue(), ^(void){                

            [self.cell.movie setContentURL:[NSURL URLWithString:videoFile.url]];
            [self.cell.movie prepareToPlay];
            [self.cell.movie play];
            self.cell.movie.view.hidden = NO;

            self.cell.photo.hidden = YES;
    });

}

在customCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {

    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];


    self.opaque = NO;
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.accessoryType = UITableViewCellAccessoryNone;
    self.clipsToBounds = NO;

    self.backgroundColor = [UIColor colorWithRed:140.0f/255.0f green:129.0f/255.0f blue:126.0f/255.0f alpha:1.0f];


    self.photo = [[PFImageView alloc]initWithFrame:CGRectMake(0, 0, window.frame.size.width, window.frame.size.width)];
    self.photo.backgroundColor = [UIColor colorWithRed:191.0f/255.0f green:191.0f/255.0f blue:191.0f/255.0f alpha:1.0f];        

    self.movie = [[MPMoviePlayerController alloc] init];
    self.movie.controlStyle = MPMovieControlStyleNone;
    self.movie.shouldAutoplay = NO;
    self.movie.repeatMode = MPMovieRepeatModeOne;
    self.movie.scalingMode = MPMovieScalingModeAspectFit;
    self.movie.movieSourceType = MPMovieSourceTypeStreaming;
    self.movie.view.backgroundColor = [UIColor clearColor];


- (void)layoutSubviews {
[super layoutSubviews];
self.movie.view.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.width);}

你的问题是你正在使用异步工作的 dispatch 函数,当单元格出队时你从 URL 执行加载,同时你向下滚动并到达也尝试的照片单元格使用 [self.cell.photo loadInBackground].

获取一些异步的东西

要解决这个问题,您需要存储一些关于异步操作的参考,例如 NSOperation,当您尝试使单元格出队时,您需要取消之前的下载过程。

我可以建议的是 google 或创建 NSOperation 队列来获取视频数据并使用 AFNetworking setImageWithURL: 来获取带有缓存的图像。