【发布时间】: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