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
}

几个星期以来,我一直试图弄清楚这一点。如果有人有更好的库来解决这个问题,请告诉我。

4

1 回答 1

1

我所做的就是像这样将我的图像存储在图像缓存中。

      private var imageCache = [String:UIImage]()

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

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

然后我将文件名存储在我的单元格数据 obj 中。

 //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 的计算机上编写的。快乐编码。

于 2016-06-04T16:57:08.260 回答