UITableView - 滚动时更改单元格图像

Tae*_*kun 7 objective-c uitableview ios

您好我的问题是,当我滚动TableView时,图像将出现在错误的单元格中,几秒钟后会出现正确的图像.

这是我的代码

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

// Configure the cell...
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}

[cell setOpaque:NO];
[cell setBackgroundColor: [UIColor clearColor]];

PlaceData *data = [tableData objectAtIndex:indexPath.row];
UILabel *nameLabel = (UILabel *)[cell viewWithTag:100];
UILabel *sciNameLabel = (UILabel *)[cell viewWithTag:200];
UIImageView *thumbnailImageView = (UIImageView *)[cell viewWithTag:300];
nameLabel.text = data.name;
sciNameLabel.text = data.scientific_name;


// get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
    NSURL *urlToPicture = [NSURL URLWithString:[NSString stringWithFormat:@"%@", data.thumbnail]];
    NSData *imgData = [NSData dataWithContentsOfURL:urlToPicture options:0 error:nil];

    // This will set the image when loading is finished
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImage *tmpImage = [[UIImage alloc] initWithData:imgData];
        thumbnailImageView.image = tmpImage;
        //dispatch_release(concurrentQueue);
         });
     });

       return cell;
 }
Run Code Online (Sandbox Code Playgroud)

请帮我

Gau*_*ava 20

您可以尝试将以下代码添加到您的cellForRowAtIndexPath -

1)为自定义单元格指定索引值.例如,

cell.tag = indexPath.row
Run Code Online (Sandbox Code Playgroud)

2)在主线程上,在分配图像之前,通过将图像与标记匹配来检查图像是否属于相应的单元格.

dispatch_async(dispatch_get_main_queue(), ^{
    if(cell.tag == indexPath.row) {
      UIImage *tmpImage = [[UIImage alloc] initWithData:imgData];
      thumbnailImageView.image = tmpImage;
    }});
 });
Run Code Online (Sandbox Code Playgroud)


Ron*_*zen 6

你正在重复使用旧细胞,这是一件好事.但是,您没有在单元格的图像视图中初始化图像,这不是一件好事.您所描述的内容是因为旧单元格(已为该单元格加载了图像)用于新单元格.然后,您将在背景中加载该单元格的图像(这也是好的)但是该图像需要一些时间才能完全加载.与此同时,显示已加载在旧单元格上的图像(这就是您在该单元格中看到错误图像的原因,片刻之后).

解决方案?添加其中一个

thumbnailImageView.image = nil
Run Code Online (Sandbox Code Playgroud)

要么

thumbnailImageView.image = someDefaultImageWhileYourRealOneLoads
Run Code Online (Sandbox Code Playgroud)

就在之前dispatch_queue_t concurrentQueue ....

这样,当真实的图像加载时,您将看不到旧的(不相关的)图像.

我希望这有帮助.祝好运.