2017-10-10 28 views
0

我有一個swift表。每當我上下滾動tableview時,即使圖像已經加載,它也會再次運行getImageForCell函數。有沒有辦法避免這種情況發生。以下是我的代碼。Swift TableView使圖像的多個網絡請求

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "ReviewTableViewCell", for: indexPath) as! ReviewTableViewCell 

    let review = json[reviewType][indexPath.row] 
    cell.nameLabel.text = review[userType]["name"].stringValue 
    cell.reviewLabel.text = review["message"].stringValue 
    cell.dateLabel.text = review["created_at"].stringValue 
    cell.ratingStars.rating = Double(review["rating"].intValue) 
    getImageForCell(url: review[userType]["photo_url"].stringValue, cell: cell) 

    return cell 
} 

func getImageForCell(url: String, cell: ReviewTableViewCell) { 
    Alamofire.request(url).responseImage { response in 
     if let downloadedImage = response.result.value { 
      print("downloaded image \(downloadedImage)") 
      DispatchQueue.main.async { 
       cell.profileImageView.image = downloadedImage 
      } 
     } 
    } 
} 
+0

「是否有此一方式不發生」那是什麼,你希望發生的方法嗎? –

+0

他意味着他不希望圖像必須每次下載,而是使用緩存圖像來避免網絡調用。 – crashlog

+0

檢查此鏈接:https://stackoverflow.com/questions/45316099/nscache-doesnt-work-with-all-images-when-loading-for-the-first-time – 3stud1ant3

回答

0

這是由於雙方沒有cacheing的圖像,也不能重複使用的單元 - 在你看來,你每次都重新創建細胞 - 這不會專門解決圖像問題,但會提高性能。我最喜歡的緩存圖片擴展名是kingfisher(無歸屬),儘管alamofire也可用於緩存圖片。

https://github.com/onevcat/Kingfisher