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

标签 ios swift uitableview uiimageview nsurlsession

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

最佳答案

我认为您只是错过了单元格 subview (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()
 }

关于ios - 如何从 UITableViewCell 内的 URL 设置 UIImageView 的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46586613/

相关文章:

Swift 如何初始化函数以提高性能

ios - 防止 UITableViewCell 向左移动并在编辑表格时出现删除按钮

swift - 添加文本后自动高度单元格

ios - 以编程方式创建不同屏幕尺寸下的对象

Swift 2 iOS 9 Do Catch 尝试崩溃并发现意外的 nil

swift - 如果来自 Alamofire 请求的响应是否为 200,我将如何更改后续 View

ios - 自动调整表格 View 单元格内的自动调整表格 View 大小

ios - 缩放 CAShapeLayer 时的意外行为

iphone - 在设备上测试 iPhone 应用程序的步骤(已创建配置文件/证书)

iphone - 如何获取(提取)iOS系统应用程序的图标,例如地址簿应用程序?