ios 中的 UIImageView 中显示了之前的视频 (AVPlayer),而不是图像

Instead of Image, previous video (AVPlayer) is showing up in in UIImageView in ios

我需要你的帮助来为我的应用程序提供 image/video。我正在使用 AVPlayer 来显示视频。

一旦显示视频,我在显示图像时遇到问题,之前的视频显示在即将到来的图像上。

这是我的代码。 userPostImageStr 中的图像 Url 是正确的,但它仍然显示最后一个视频。

if (userPostVideo != (NSString *)[NSNull null])
{
   AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];

    AVPlayer *player = [[AVPlayer alloc] init];

    NSURL *url = [NSURL URLWithString:userPostVideo];

    AVURLAsset *asset = [AVURLAsset assetWithURL:url];

    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];

    player = [[AVPlayer alloc] initWithPlayerItem:item];

    playerViewController.player = player;

    [playerViewController.view setFrame:cell.userPostImage.frame];

    playerViewController.showsPlaybackControls = NO;

    [cell.userPostImage addSubview:playerViewController.view];

    [player play];
}

else if (userPostImageStr != (NSString *)[NSNull null])
{
    if (userPostImageStr != (NSString *)[NSNull null])
    {
        [cell.userPostImage setShowActivityIndicatorView:YES];
        [cell.userPostImage setIndicatorStyle:UIActivityIndicatorViewStyleGray];

        [cell.userPostImage sd_setImageWithURL:[NSURL URLWithString:userPostImageStr]
                          placeholderImage:[UIImage imageNamed:@"appIcon"] options: SDWebImageRefreshCached
                                 completed:^(UIImage image, NSError error, SDImageCacheType cacheType, NSURL *imageURL)
         {

             if (image.size.width < cell.contentView.frame.size.width)
             {
                 // NEED to write the for contraint update at runtime
                 //[postImageView setConstraintConstant:image.size.width forAttribute:NSLayoutAttributeWidth];
             }

         }];
    }
}
else
{
    cell.userPostImage.image = [UIImage imageNamed:@"appIcon"];
}

如果有人知道这个问题,请回复。

谢谢。

问题是您将包含播放器的子视图添加到单元格,而没有删除子视图。这就是你打电话时发生的事情

[cell.userPostImage addSubview:playerViewController.view];

当单元格被重用时,之前添加的视图仍然存在并导致各种意外行为。

在添加子视图之前,您应该通过调用

删除现有视图
[theViewToBeRemoved removeFromSuperView];

这需要您保留对视图的引用。一种方法是在视图上设置标签。例如:

// Set the tag on the view.
playerViewController.view.tag = 1000;

// Remove the view with the matching tag.
[[cell.userPostImage viewWithTag:1000] removeFromSuperView];

我还建议让玩家成为您的单元格子类中的 属性 以保持一切井井有条。