UITableView - 滚动时更改单元格图像 [英] UITableView - cell images changing while scrolling

查看:124
本文介绍了UITableView - 滚动时更改单元格图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi my problem is that when I scroll TableView the image will appear in a wrong cell, after a few seconds the correct image appears.

这是我的代码

 - (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;
 }

请帮帮我

推荐答案

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

You can try adding following code to your cellForRowAtIndexPath -

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

1) Assign an index value to your custom cell. For instance,

cell.tag = indexPath.row

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

2) On main thread, before assigning the image, check if the image belongs the corresponding cell by matching it with the tag.

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

这篇关于UITableView - 滚动时更改单元格图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆