在 UITableViewCell 中延迟加载图像 [英] Lazy load images in UITableViewCell

查看:27
本文介绍了在 UITableViewCell 中延迟加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 UITableView 中有大约 50 个自定义单元格.我想在从 URL 获取图像的单元格中显示图像和标签.

I have some 50 custom cells in my UITableView. I want to display an image and a label in the cells where I get the images from URLs.

我想延迟加载图像,以便在加载图像时 UI 不会冻结.我尝试在单独的线程中获取图像,但每次单元格再次可见时我都必须加载每个图像(否则重复使用单元格会显示旧图像)

I want to do a lazy load of images so the UI does not freeze up while the images are being loaded. I tried getting the images in separate threads but I have to load each image every time a cell becomes visible again (Otherwise reuse of cells shows old images)

像 Facebook 这样的应用程序只为当前可见的单元格加载图像,一旦图像被加载,它们就不会再次加载.有人可以告诉我如何复制这种行为.

Apps like Facebook load images only for cells currently visible and once the images are loaded, they are not loaded again. Can someone please tell me how to duplicate this behavior.

谢谢.

编辑
当用户快速滚动时,尝试在 NSMutableDictionary 对象中缓存图像会产生问题.仅当滚动完全停止并清除内存警告缓存时,我才能获取图像.但是应用程序总是会收到内存警告(由于缓存的图像大小)并在重新加载之前清除缓存.如果滚动速度非常快,它就会崩溃.

Edit
Trying to cache images in an NSMutableDictionary object creates problems when the user scrolls fast. I am getting images only when scrolling completely stops and clearing out the cache on memory warning. But the app invariably gets a memory warning (due to size of images being cached) and clears the cache before reloading. If scrolling is very fast, it crashes.

欢迎任何其他建议

推荐答案

在后台线程上加载图像仍然是一个好主意.如果您不想每次都重新加载它们,我建议设置一个 NSMutableDictionary 并将图像存储在那里.您可以使用某些唯一标识符(例如行 ID 甚至图像名称)作为每个图像的键.

Loading the images on a background thread is still a good idea. If you didn't want to reload them each time, I'd suggest setting up an NSMutableDictionary and storing the images in there. You could use some unique identifier, like the row ID or even the name of the image, as the key for each image.

加载单元格时,您需要向 NSMutableDictionary 发送 objectForKey: 消息以检索该特定单元格的图像(基于您的唯一键).如果它返回 nil,则意味着图像从缓存中丢失,您需要背景图像加载线程来检索它.否则,您将获得要显示的表格单元格的适当图像.出现内存警告时,您可以清除此图像缓存而不会产生不利影响(除了强制它们按需重新加载).

When loading a cell, you'd send an objectForKey: message to the NSMutableDictionary to retrieve the image for that particular cell (based on your unique key for it). If it returns nil, that means that the image is missing from the cache and you need your background image loading thread to go retrieve it. Otherwise, you will get back the appropriate image for your table cell to display. On a memory warning, you could clear out this cache of images with no adverse effects (aside from forcing them to be reloaded again on demand).

这篇关于在 UITableViewCell 中延迟加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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