Swift - UITableView - 快速滚动时加载错误的图片

4

我正在使用Haneke库来下载、加载和缓存图片。这个库很好用,但是在快速滚动时,它会加载错误的图片,或者有时根本不会加载任何图片。

这是因为在后台下载的速度跟不上快速滚动的速度,所以队列中下一个要加载的图片可能会被加载到错误的单元格中。

以下是请求网络图片和缓存图片的代码:

let fetcher_net = NetworkFetcher<UIImage>(URL: finished_URL!)
        let fetcher_disk = DiskFetcher<UIImage>(path: check_apost)
        cache.fetch(fetcher: fetcher_disk).onSuccess { image in
            //cell.card_imageIV.hnk_fetcher.cancelFetch()
            //print("Image Cache found")
            cell.card_imageIV.image = image
            }.onFailure{ image in
                //print("Unavailable to find image cache, fetching from network")
                cache.fetch(fetcher: fetcher_net).onSuccess { image in
                    //print("Network image request SUCCESS")
                    cell.card_imageIV.image = image
                }
        }

同时,在自定义单元格的Swift文件中,是否有任何方法可以在屏幕上的单元格消失时终止任何请求?

override func prepareForReuse() {
    super.prepareForReuse()
    // Increment the generation when the cell is recycled

    //card_imageIV.hnk_cancelSetImage()
    //card_imageIV.image = nil
}

我已经试图想解决这个问题好几周了。如果有更好的库可以用来解决此问题,请告诉我。

1个回答

1
我所做的是将图片存储在图像缓存中,像这样。
      private var imageCache = [String:UIImage]()

一旦我从任何地方获取了图像,我就将UIImage存储在我的imageCache数组中。

     self.imageCache["myImageFilename-01"] = img
     self.imageCache["myImageFilename-02"] = img2 
     etc....

然后我将文件名存储在我的单元格数据对象中。
 //Basic structure example.
 class myData: NSObject
    {
     var imageFilename : String?
     var titleText : Double?
     etc...
    }   

将数据存储在obj中,并将obj存储在数组中。这将在以后用于获取您的数据。

 let newObj = myData()
     newObj.imageFilename = "myImageFilename-01"
     newObj.titleText = "some title text"
  myDataArray.append(newObj)

然后您可以这样设置图像。
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("TableCell", forIndexPath: indexPath) as! MyCustomCellClass

    //I like to clear the image. Just incase. Not sure it is needed to do.
     cell.myCellImage.image = nil //Or what ever you have wired up.

   //Get the data from your array of myDataArray
    let rowData  = myDataArray[indexPath.row]

    cell.myCellImage.image = self.imageCache[rowData.imageFilename]

   //Set the rest of your cell stuff

   return cell.
   }

我认为这会让你朝着正确的方向前进。我想可能会有一些语法问题,因为我是在没有Xcode的电脑上编写的。愉快的编程。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接