2017-07-08 72 views
0

我做了一個自定義的TableView,它有一個圖像視圖和一些從API獲取值的標籤。從iOS的ImageView中的API的多次加載圖像

這是一個自定義表格,圖像和標籤從API接收與房地產相關的數據。

當我的自定義表加載時,值開始來自API。

圖像視圖中的實際問題ocurr。我在圖像視圖中設置了一個本地圖像,當來自API的數據沒有圖像時,應該顯示本地圖像,否則數據應該顯示客戶在表單中提交的原始圖像。

現在,當數據從API首先在圖像視圖中顯示時,它會顯示本地圖像,而不是圖像從API開始顯示時顯示,但當我們在圖像視圖中向下滾動時,它會在圖像視圖中顯示相同圖像並重復多次,我們無法確定哪個是原始圖像。

我可以提供代碼,如果有人給我發了他的電子郵件,他可以得到所有的工作。

enter image description here

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *[email protected]"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; 
} 
+1

您需要編輯您的問題以包含相關代碼。特別是你的'cellForRow(at:)'方法。當你的表滾動時,你幾乎肯定不會考慮單元重用;在這個網站上有無數類似的問題 – Paulw11

+0

每次抓取圖像效率不高。您應該使用某種緩存,例如SDWebImage。此外,您並未在下載開始前設置佔位符圖像,因此圖像視圖將包含最後放入其中的任何圖像。在閉包中,您可能還想檢查單元格的索引路徑是否是剛下載的映像的索引路徑,因爲表格可能已滾動,並且自您開始下載後單元格會被重用。 – Paulw11

+0

可以請你解釋一下,如果我使用郵件發送你的項目。 @ Paulw11 –

回答

2

看來你並沒有將圖像存儲到本地應用程序內存中。您嘗試每次出現單元格時加載圖像。所以你每次下載圖片。

最好的解決方案:

你需要使用SDWebImage存儲圖像的本地存儲器。

的Objective-C:

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

斯威夫特:

import SDWebImage 

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

如果要加載的第一次圖像,然後它會下載和圖像存儲到本地內存。所以從第二次開始,它將從本地加載。

+0

非常感謝。 @Nirmalsinh –

0

那麼,它因爲你的電池得到重新使用和正在顯示一個圖像。您可以覆蓋你的tableviewcell子類的prepareForReuse()方法或考慮使用SDWebImage

編輯URL圖像設置佔位符:釋

您正在下載圖像ASYC並將其設置爲你的tableviewcell的ImageView的是什麼這裏發生的是在你的下一張圖像被下載的時候,在這之前你的單元格被重新使用並顯示之前的圖像。