2017-10-05 90 views
0

我有cellForRowAt方法獲取圖像並加載到單元格的imageView中的以下代碼。確認圖像是從打印語句下載的,但圖像未顯示在單元格中。請幫幫我。如何從UITableViewCell中的URL設置UIImageView的圖像?

let request = URLRequest(url: URL(string: imageURL)!) 

     let session = URLSession.shared 
     let dataTask = session.dataTask(with: request as URLRequest) {(data, response, error) in 
      // The download has finished. 
      if let e = error { 
       print("Error downloading picture: \(e)") 
      } else { 
       // No errors found. 
       // It would be weird if we didn't have a response, so check for that too. 
       if let res = response as? HTTPURLResponse { 
        print("Downloaded image with response code \(res.statusCode)") 
        if let imageData = data { 
         // Finally convert that Data into an image and do what you wish with it. 
         let image = UIImage(data: imageData) 
         // Do something with your image. 

         DispatchQueue.main.async { 
          cell.imgView.contentMode = .scaleAspectFit 
          cell.imgView.image = image 
         } 

         print("image received") 
        } else { print("Couldn't get image: Image is nil") } 
       } else { print("Couldn't get response code for some reason") } 
      } 
     } 
     dataTask.resume() 
+0

您是否在設置圖像時檢查'cell.imgView'是否不是'nil'? –

+0

@SalmanGhumsani我想使用Apple提供的本地庫而不是AlamoFire。感謝您的迴應。 –

+0

你有沒有在調試過程中瞭解'cell'的價值?和'cell.imgView'?他們有效嗎? – DonMag

回答

0

我想你只是想重新加載你的單元格的子視圖(imageView)來顯示圖像。你也可能想跟蹤正確的單元格。

cell.tag = indexPath.row //after you init the cell 

DispatchQueue.main.async { 
    if cell.tag == indexPath.row 
    cell.imgView.contentMode = .scaleAspectFit 
    cell.imgView.image = image 
    cell.setNeedsLayout() 
} 
相關問題