在UITableViewCell中异步加载图像的超级简单方法是什么?假设给定一个imageURL而不必为UITableViewCell创建子类,即:标准UITableViewCell
答案 0 :(得分:1)
我知道最简单的方法是使用SDWebImage库。这是一个链接,解释了如何利用SDWebImage库异步加载化身。
SDWebImage是ImageView的扩展。以下是用法:
// load the avatar using SDWebImage
[cell.imageView setImageWithURL:[NSURL URLWithString:tweet.profileImageUrl]
placeholderImage:[UIImage imageNamed:@"grad_001.png"]];
以下是引用的文章:
答案 1 :(得分:1)
在.m中,包含目标c运行时:
#import <objc/runtime.h>
在@implementation部分的顶部,定义一个静态常量供以下使用:
static char * const myIndexPathAssociationKey = "";
在您的cellForRowAtIndexPath中,添加以下代码:
// Store a reference to the current cell that will enable the image to be associated with the correct
// cell, when the image subsequently loaded asynchronously. Without this, the image may be mis-applied
// to a cell that has been dequeued and reused for other content, during rapid scrolling.
objc_setAssociatedObject(cell,
myIndexPathAssociationKey,
indexPath,
OBJC_ASSOCIATION_RETAIN);
// Load the image on a high priority background queue using Grand Central Dispatch.
// Can change priority by replacing HIGH with DEFAULT or LOW if desired.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^{
UIImage *image = ... // Obtain your image here.
// Code to actually update the cell once the image is obtained must be run on the main queue.
dispatch_async(dispatch_get_main_queue(), ^{
NSIndexPath *cellIndexPath = (NSIndexPath *)objc_getAssociatedObject(cell, myIndexPathAssociationKey);
if ([indexPath isEqual:cellIndexPath]) {
// Only set cell image if the cell currently being displayed is the one that actually required this image.
// Prevents reused cells from receiving images back from rendering that were requested for that cell in a previous life.
[cell setImage:image];
}
});
}];
最后,为了在旧设备上快速滚动时支持最佳性能,您可能需要先加载最近请求的图片...为此,请参阅this thread for asynchronously loading cell images using a last-in first-out stack and GCD。
答案 2 :(得分:0)
您可以使用线程。首先将按钮放在字典上。然后使用线程。最后在 setImage:方法中,您可以放置图像。
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:url forKey:@"url"];
[dictionary setObject:image forKey:@"image"];
[NSThread detachNewThreadSelector:@selector(setImage:)
toTarget:self
withObject:dictionary];