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

时间:2023-01-24 16:43:34

I have the following code inside cellForRowAt method to fetch image and load into the cell's imageView. The image is confirmed to be downloaded from the print statements, but image is not showing in the cell. Please help me.

我在cellForRowAt方法中有以下代码来获取图像并加载到单元格的imageView中。确认图像从打印语句下载,但图像未显示在单元格中。请帮帮我。

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()

1 个解决方案

#1


0  

I think you just missing a reload of your cell's subviews (imageView) to show the image. You also probably want to keep track of the right cell.

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

#1


0  

I think you just missing a reload of your cell's subviews (imageView) to show the image. You also probably want to keep track of the right cell.

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