我正在通过关注 this wonderful tutorial 来学习 iOS 编程, 除了我的目标是 iOS 9 并做了一些小的修改。
在下面的 tableView() 函数中,我可以下载缩略图并调用我的处理程序,从控制台打印出的两条日志记录行可以看出这一点。但是,当应用程序运行时(在模拟器中),我必须单击每个表格单元格才能显示图像。我试图查看 UIImageView
或表格单元格中是否有 refresh()
或类似的东西,但一无所获。
如何让图片在收到数据后立即显示出来?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)!
let album = self.albums[indexPath.row]
// ... setting up other cell's data, see the tutorial link
// Start by setting the cell's image to a static file
// Without this, we will end up without an image view!
cell.imageView?.image = UIImage(named: "Blank52")
let request: NSURLRequest = NSURLRequest(URL: thumbnailURL)
let urlSession = NSURLSession.sharedSession()
urlSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) -> Void in
print("received thumbnail \(thumbnailURLString)") // reached
if error == nil {
// Convert the downloaded data in to a UIImage object
let image = UIImage(data: data!)
// Update the cell
dispatch_async(dispatch_get_main_queue(), {
print("...dispatched thumbnail image for \(thumbnailURLString)") // reached
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView?.image = image
}
})
}
}).resume()
return cell
}
最佳答案
这部分没有意义:
if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
cellToUpdate.imageView?.image = image
这似乎是在创建一个无限循环。每次调用 cellForRowAtIndexPath
都会导致 另一个 调用 cellForRowAtIndexPath
。
我想你的意思是:
cell.imageView?.image = image
你已经知道这个单元格了。您刚刚在调用此 block 之前创建了它。您无需再次查找。
关于swift - iOS UIImageView 不自动刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33537564/