TableView图像直到滚动才加载 [英] TableView Images does not load until scrolling

查看:153
本文介绍了TableView图像直到滚动才加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Firebase 将我的图片加载到我的单元格 ImageView 中,但是!有一个问题。我正在使用缓存机制,以防止图像重新下载可重复使用的单元格加载,但图像不加载,直到我滚动我的 TableView

以下是代码;

  public func tableView(_ tableView:UITableView,cellForRowAt indexPath:IndexPath) - > UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier:cell)as! TableViewCell
cell.imgv.image = nil

如果让urlString = self.filteredFlats [indexPath.row] .flatThumbnailImage?.imageDownloadURL
{
imageURLString = urlString

让url = URL(string:urlString)
if imagefromCache = imageCache.object(forKey:urlString as AnyObject)as? UIImage
{
DispatchQueue.main.async {
cell.imgv.image = imagefromCache
return
}
}
else



中的URLSession.shared.dataTask(with:url !, completionHandler:{(data,response,error))DispatchQueue.main.async {

让imagetoCache = UIImage(data:data!)

if self.imageURLString == urlString
{
cell.imgv.image = imagetoCache

}
self.imageCache.setObject(imagetoCache !, forKey:urlString as AnyObject)

$ b})。resume()
}
}
返回单元格
}

我认为问题是,当 URLSession 下载了图像并将其设置为 ImageView ,但是loa直到 indexpath.row 上下滚动时,ded image才显示出来。

原因是这个if语句;

pre $ if self.imageURLString == urlString

但是,如果我删除它,单元格变得更糟糕的可重用单元格的行为。有些单元格仍然显示旧的缓存图像。



真的不知道发生了什么。不要指望 TableViews 是一种复杂的结构。



谢谢。

解决方案

是从YouTube上的iOS教程学习的。
我们可以创建一个 CustomImageView 类,并且让imageCache = NSCache< AnyObject,AnyObject>()保存图片缓存。当滚动tableview的时候,如果有imageView的imageCache,我们直接使用它。但是如果不存在的话,我们会下载带有图片URL字符串的图片并保存。

  import UIKit 

imageCache = NSCache< AnyObject,AnyObject>()

class CustomImageView:UIImageView {

var imageUrlString:String?

func loadImageWithString(_ urlString:String){
$ b $ imageUrlString = urlString

let request = URLRequest(url:URL(string:urlString)! )

self.image = nil

// imageCache存在,直接使用
if imageFromCache = imageCache.object(forKey:urlString as AnyObject)as ? UIImage {

self.image = imageFromCache
}

// imageCache不存在,然后下载图像并保存
URLSession.shared .dataTask(with:request,completionHandler:{(data,response,error)in

guard let data = data,error == nil else {
print(error?.localizedDescription as Any )
返回
}

DispatchQueue.main.async(){

let imageToCache = UIImage(data:data)

imageCache.setObject(imageToCache!forKey:urlString as String as AnyObject)

if self.imageUrlString == urlString {

self.image = imageToCache
}

$ b})。resume()

}

}

而在自定义单元格的Class文件中,我们可以这样使用它:

  if imageUrlString = thumbnailUrlString {
thumbnailImageView.loadImageWithString(imageUrlString)
}

请注意,1,thumbnailImageView:CustomImageView
2,thumbnailUrlString是可选的


I'm using Firebase to load my images into my cell's ImageView but! there is a problem. I'm using caching mechanism for preventing images to redownload when reusable cells loads but the images do not load until i've scroll my TableView.

Here is the code;

     public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
    cell.imgv.image = nil

if let urlString =  self.filteredFlats[indexPath.row].flatThumbnailImage?.imageDownloadURL
    {
        imageURLString = urlString

        let url = URL(string: urlString)
        if let imagefromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage
        {
            DispatchQueue.main.async {
                cell.imgv.image = imagefromCache
                return
            }
        }
        else
        {

            URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
                DispatchQueue.main.async {

                    let imagetoCache = UIImage(data:data!)

                    if self.imageURLString == urlString
                    {
                        cell.imgv.image = imagetoCache

                    }
                    self.imageCache.setObject(imagetoCache!, forKey: urlString as AnyObject)

                }
            }).resume()
        }
    }
    return cell
}

I think the problem is, when URLSession downloaded the image and set it into ImageView, but the loaded image is not showing up until the indexpath.row called back when scrolling up and down.

I realized that the cause of it is this if statement;

 if self.imageURLString == urlString

But if i remove it, the cells getting worse coz of reusable cell's behaviour. Some cells still showing the old cached images.

Really does not aware of what is going on. Was not expecting that TableViews are kind of complex structure as it is.

Thanks.

解决方案

I solve it with the following method which is learned from an iOS tutorial on YouTube. We can create a CustomImageView class, and let imageCache = NSCache<AnyObject, AnyObject>() to save the image Cache.When scrolling the tableview,if there is an imageCache for the imageView, we use it directly.But if it doesn't exsit, we will download the image with image URL string and save it.

import UIKit

let imageCache = NSCache<AnyObject, AnyObject>()

class  CustomImageView: UIImageView {

    var imageUrlString :String?

    func loadImageWithString(_ urlString:String){

        imageUrlString = urlString

        let request = URLRequest(url: URL(string:urlString)!)

        self.image = nil

        //imageCache exist,and use it directly
        if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {

            self.image = imageFromCache
        }

        //imageCache doesn't exist,then download the image and save it
        URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in

            guard let data = data, error == nil else {
                print(error?.localizedDescription as Any)
                return
            }

            DispatchQueue.main.async() { 

                let imageToCache = UIImage(data: data)

                imageCache.setObject(imageToCache!, forKey: urlString as String as AnyObject )

                if self.imageUrlString == urlString{

                    self.image = imageToCache
                }
            }

        }).resume()

    }

}

And in the custom cell Class file, we can use it as follows:

 if let imageUrlString = thumbnailUrlString {
               thumbnailImageView.loadImageWithString(imageUrlString)
            }

Note that 1,thumbnailImageView :CustomImageView 2, thumbnailUrlString is optional

这篇关于TableView图像直到滚动才加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆