【问题标题】:How to set an image for a UIImageView from a URL inside a UITableViewCell?如何从 UITableViewCell 中的 URL 为 UIImageView 设置图像?
【发布时间】:2017-10-05 13:16:33
【问题描述】:

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

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

【问题讨论】:

  • 设置图片时是否检查cell.imgView 不是nil
  • @SalmanGhumsani 我想使用 Apple 提供的本地库而不是 AlamoFire。感谢您的回复。
  • 你有没有通过调试来查看cell 的值是多少?和cell.imgView?它们有效吗?
  • @asdiu - 由于您想避免使用第 3 方库,您可能希望采用使用 UIImageView 扩展的方法,而不是您的代码块(我假设它在 cellForRowAt ?)。这可以用于任何图像视图,而不仅仅是在表格单元格内:stackoverflow.com/a/39339641/6257435
  • 第一个问题:您不可能忘记将 imgView 作为子视图添加到您的单元格中吗?第二个问题:您是否尝试过将图像作为参数存储到您的单元子类中?如果这样做,您可以通过 didSet 观察者检查传递给单元格的值,并将图像分配给图像视图并在图像值更改时调用 setNeedsDisplay。

标签: ios swift uitableview uiimageview nsurlsession


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 1970-01-01
    • 2023-03-19
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多