在UITableViewCellasynchronous加载图像

什么是超级非常简单的方法来加载UITableViewCell中的图像asynchronous地说给一个imageURL而不必inheritanceUITableViewCell,即:标准的UITableViewCell

我知道的最简单的方法是使用SDWebImage库。 这是一个链接,介绍如何利用SDWebImage库asynchronous加载头像。

SDWebImage是ImageView的扩展。 这是用法:

// load the avatar using SDWebImage [cell.imageView setImageWithURL:[NSURL URLWithString:tweet.profileImageUrl] placeholderImage:[UIImage imageNamed:@"grad_001.png"]]; 

这里是引用的文章:

实施Twittersearch

在你的.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]; } }); }]; 

最后,为了在旧设备上快速滚动时支持最佳性能,您可能需要首先加载最近请求的图像…为此,请参阅此线程以使用后进先出堆栈和GCDasynchronous加载单元格图像 。

你可以使用一个线程。 将button放在字典上。使用线程。 然后在setImage方法中你可以放置图像。

 NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; [dictionary setObject:url forKey:@"url"]; [dictionary setObject:image forKey:@"image"]; [NSThread detachNewThreadSelector:@selector(setImage:) toTarget:self withObject:dictionary];