无法将图像加载到 swift 中的单元格

Failure in loading image to cell in swift

我刚开始使用 swift。我正在使用块和 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() 的完成块中成功获取图像,但是,我无法更新单元格。对于上面的代码,下载的图像应用于 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
                }
            })

这给了我完美的解决方案