gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:06:48 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com