0

我正在开发一个显示图像的 tableView,并且每次加载视图时都会重新下载图像。有没有办法缓存图像,所以它只下载一次图像?(缓存图片)

4

1 回答 1

1

你可以这样做:

在您的 tableViewDelegate 创建一个 Cache 对象

var myCache = NSCache()

然后在 rowAtIndexPath

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    if let row = tableView.dequeueReusableCellWithIdentifier("MyCell") as? MyCell{


        //Get the item
        let item = items[indexPath.row]

        //You need to cancel previous requests and reset the image to avoid render errors caused by the reusable row
        //here you should also cancel any previous requests made to avoid downloading an image that the user won't see because he scrolled 
        cell.img.image = nil

        //Search for the image in the cache
        var img:UIImage?
        img = myCache.objectForKey(item.image_url) as? UIImage

        row.configureCell( item: item,img:img)

        return row

    }else{
        return MyCell()
    }
}

最后在牢房里

func configureCell(item:Item,image:UIImage?){
    self.item = item


    if image != nil{
        //The image exist so you assign it to your UIImageView
        img.image = image
    }else{
        //Create the request to download the image
    }

}
于 2016-06-02T23:53:40.593 回答