如何从UITableViewCell中的URL设置UIImageView的图像?

问题描述:

我有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

我想你只是想重新加载你的单元格的子视图(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() 
}