swift - iOS UIImageView 不自动刷新

标签 swift uiimageview uikit ios9

我正在通过关注 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/

相关文章:

xcode - swift ,Xcode : Changing UIButton Background and Text on Click

swift - 如何在 Swift 2 中将 Array<String> 添加到 Dictionary<String, AnyObject>

iphone - 在 UIImageView 中旋转图像

ios - 如果我已经提供了 Controller ,如何提供 Adyen 结账?

ios - 来自 mySQL 数据库 iOS/Swift 的循环 URL

ios - 引用另一个 UIViewController 导致一个 nil 指针并创建一个新对象

iOS 纵横比填充图像调整大小,内容与左/上边缘对齐

ios - 图像不适合 UIImageView

ios - 如何同时获取键盘的大小和选中的 UITextField 的 CGFrame?

objective-c - 在 UITableViewCell 中调整 UIImageView 的大小