代码之家  ›  专栏  ›  技术社区  ›  Hamza Imran

在IOS的ImageView中多次从API加载图像

  •  0
  • Hamza Imran  · 技术社区  · 9 年前

    这是一个自定义表,其中图像和标签从与房地产相关的API接收数据。

    图像视图中的实际问题ocurr。我在图像视图中设置了一个局部图像,当来自API的数据没有图像时,它应该显示局部图像,否则数据应该显示客户在表单中提交的原始图像。

    现在,当数据首先在图像视图中来自API时,它显示的是局部图像,而当图像开始来自API时,它开始显示,但当我们在图像视图中向下滚动时,它在图像视图中显示相同的图像,并重复多次,我们无法识别哪个是原始图像。

    enter image description here

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *cellIdentifier=@"Cell";
        CustomTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
        StringData* cust = [_Title objectAtIndex:indexPath.row];
    
        cell.Title.text = cust.title1;
        cell.area.text=cust.Area;
        cell.city.text=cust.City;
        cell.phone.text=cust.phoneno;
        cell.price.text=cust.Price;
        cell.location1.text=cust.location;
        cell.name1.text=cust.dealer_name;
        cell.email1.text=cust.dealer_email;
        cell.type1.text=cust.property_type;
        cell.status1.text=cust.status;
        cell.room1.text=cust.rooms;
        cell.washrooms.text=cust.bath;
        cell.floor1.text=cust.floors;
        cell.imagetext.text = cust.images;
    
        tii=cell.Title.text;
        NSLog(@"Tittttttle is %@",tii);
    
    
        NSURL *url = [NSURL URLWithString:cust.images];
        NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,    NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data) {
                UIImage *image = [UIImage imageWithData:data];
                if (image) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        cell.images1.image = image;
                    });
                }
            }
        }];
        [task resume];
    
        return cell;
    }
    
    2 回复  |  直到 9 年前
        1
  •  4
  •   Nirmalsinh Rathod    9 年前

    最佳解决方案:

    您需要使用 SDWebImage

    目标C:

    #import <SDWebImage/UIImageView+WebCache.h>
    ...
    [imageView sd_setImageWithURL:[NSURL URLWithString:@"IMAGE_URL"]
                 placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    

    Swift:

    import SDWebImage
    
    imageView.sd_setImage(with: URL(string: "IMAGE_URL"), placeholderImage: UIImage(named: "placeholder.png"))
    

    如果您是第一次加载图像,那么它将下载图像并将其存储到本地内存中。所以从第二次开始,它将从本地本身加载。

        2
  •  0
  •   Pratik Jamariya    9 年前

    prepareForReuse() 方法或考虑使用设置url图像的占位符 SDWebImage

    您正在下载图像asyc并将其设置为tableviewcell的imageview,这里发生的事情是在下载下一个图像时,在此之前,您的单元格将被重新使用并显示上一个图像。

    推荐文章