ios - 无法快速将图像加载到单元格

标签 ios iphone swift uitableview ios8

我刚刚开始使用 swift。我正在使用 block 和 NSOperationQueue 下载 tableViewCell 中的图像,并在完成处理程序中返回下载的图像。我正在尝试按如下方式更新单元格。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("itemCell", forIndexPath: indexPath) as! UITableViewCell

        var itemImage = cell.viewWithTag(1000) as! UIImageView
        var itemName = cell.viewWithTag(1001) as! UILabel

        if let item = self.itemArray?[indexPath.row] {
            itemImage.image = UIImage(named: "Placeholder.jpg")
            getImageForItem(item, withCompletion: { (image) -> () in
                if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                    var imageViewToUpdate = cellToUpdate.viewWithTag(1000) as! UIImageView
                    imageViewToUpdate.image = image
                }
            })

            itemName.text = item.itemName
            }
        return cell
    }

func getImageForItem(item: item, withCompletion completion:((image: UIImage) -> ())) {
        if let image = self.imageCache.objectForKey(item.itemID) as? UIImage {
            completion(image: image)
        } else {
            let request = item.getItemImage(ItemImageSize(rawValue: 2)!, withWidth: 100, shouldFetch: false, block: { (image, tempID) -> Void in
                if image != nil {
                    self.imageCache.setObject(image, forKey: item.itemID)

                    if item.itemID == tempID {
                        completion(image: image)
                    }
                }
            })
            if request != nil {
                imageQueue.addOperation(request)
            }
        }
    }

我面临的问题是,我在 cellForRowAtIndexPath() 的完成 block 中成功获取图像,但是,我无法更新单元格。对于上面的代码,下载的图像应用于 tableView 中的所有可见单元格,但是,当我向下滚动时,我只看到占位符图像。即使我在向后滚动时将加载的图像松散到占位符图像。

在调试时,我发现

if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) {
                    var imageViewToUpdate = cellToUpdate.viewWithTag(1000) as! UIImageView
                    imageViewToUpdate.image = image
                }

循环仅在第一次可见单元格时被调用。但不会在滚动时再次调用。我错过了什么?

最佳答案

我自己解决了。我又添加了一个参数 indexPath 来跟踪它。

getImageForItem(item, indexPath: indexPath, withCompletion: { (image, imageIndexPath) -> () in
                if Set<NSIndexPath>(tableView.indexPathsForVisibleRows() as! [NSIndexPath]).contains(imageIndexPath) {
                    itemImage.image=image
                }
            })

这给了我完美的解决方案

关于ios - 无法快速将图像加载到单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560682/

相关文章:

ios - Swift 2 reloadData 向 UICollectionView 添加了更多单元格

iphone - 验证 UITextField

ios - 带按钮的一个 ViewController 中的多个音频文件

ios - Scrollview 中的两个动态 Stackview

ios - Swift:ImageView 方面填充错误

ios - 我怎样才能同时在内存中使用默认 Realm 和 Realm ?

ios - .xib 文件中的多语言标签更改。

ios - 如何在iOS的对象库中使用 "pdfView"?

iphone - 在默认日历中添加特定日期作为事件

html - 如何解析 HTML 以搜索特定内容的针