Swift - UITableView - 快速滚动时加载不正确的图像

标签 swift image uitableview haneke

我正在使用 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
}

几周来我一直在努力解决这个问题。如果有人有更好的库来解决这个问题,请告诉我。

最佳答案

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

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

关于Swift - UITableView - 快速滚动时加载不正确的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37221383/

相关文章:

swift - 尾随闭包传递给不接受闭包的 'Set<HTTPMethod>' 类型的参数

ios - @2x 不完全是 2x 时的问题

jquery - 制作一个带背景的按钮

iOS tableView 分页

ios - 为 UITableView 的每一行推送不同的 UIView

iOS:自定义 TableView 单元来模仿音乐播放器

swift - 不明白这个尾随闭包

ios - 核心数据错误:如果没有在范围内使用NSManagedObjectContext,则无法获取

ios - AVFoundation:标签栏上的 "Flip camera"按钮

html - 如何垂直对齐 figcaption 到图中的 img