在tableview中延迟加载图像
我试图加载我的uitableviewcells在懒惰模式的形象。
我试图以最简单的方式来做,我看到了很多例子,但是它们比我的目的要进一步。
这是我目前正在做的,而不是工作:
// Configure the cell... Info *info = [self.Array objectAtIndex:indexPath.row]; cell.textLabel.text = info.name; cell.detailTextLabel.text = info.platform; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //The image is downloaded in asynchronous NSBlockOperation *downloadingImgBlock = [NSBlockOperation blockOperationWithBlock:^{ NSString* imageURL = info.imgURL; NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imageURL]]; cell.imageView.image = [UIImage imageWithData:imageData]; }]; [self.queue addOperation:downloadingImgBlock];
为什么它不工作? 它怎么能工作?
男人, AsyncImageView是你的朋友! 只需设置图像url,一切都为您处理,下载,caching。 这很棒。
尝试下面的代码
...... __block UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; __block UIImage *img; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imageURL]]]; dispatch_async(dispatch_get_main_queue(),^{ cell.imageView.image = img; } }); }); ......
使用第三方库源代码将是最简单的,但这是你如何在代码中做到这一点。 你将要在你的.h
或者.m
的顶部创build一个NSMutableArray
作为属性,如下所示:
@implementation viewController{ NSMutableArray *picList; }
并在-initWithCoder:
或者,无论你是超载的init:
picList = [[NSMutableArray alloc] init];
in – tableView:cellForRowAtIndexPath:
fullPicURL是URL):
if([self imageExists:fullPicURL]){ shoePic = [picList objectForKey:fullSmallPicURL]; } else { NSURL *picURL = [NSURL URLWithString:fullPicURL]; shoePic = [UIImage imageWithData:[NSData dataWithContentsOfURL:picURL]]; NSDictionary *thisImage = [NSDictionary dictionaryWithObject:shoePic forKey:fullSmallPicURL]; [cachedImages addEntriesFromDictionary:thisImage]; }
其中-imageExists:
是你写的一个函数,它检查字典中的url。 对象是图片本身,关键是url。 然后你做cell.image = showPic;
,或者任何你想调用它的东西,而你已经完成了caching。 为了加载他们asynchronous,做到这一点:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSData *data = [NSData dataWithContentsOfURL:shoes]; [self performSelectorOnMainThread:@selector(fetchedShoeData:) withObject:data waitUntilDone:YES]; });
并在fetchedData结尾:
[self.tableView reloadData];
那么只要确保你编辑了–numberOfSectionsInTableView:
如果它必须改变自己。 可能是其他一些事情,你需要做的100%的工作,让我知道
试试这个,我总是使用这种schemeasynchronous加载图像:
(我没有find最简单的方法。)
- (void)inAnyMethod { // ... void (^blockLoadPhoto)() = ^{ UIImage *_imageTemporary = [UIImage imageNamed:@"..."]; if (_imageTemporary) { [self performSelectorOnMainThread:@selector(setPhoto:) withObject:_imageTemporary waitUntilDone:true]; } }; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), blockLoadPhoto); // ... } - (void)setPhoto:(UIImage *)photo { // do something with the loaded image }
我终于设法做到这一点:
– performSelectorOnMainThread:withObject:waitUntilDone:
图像下载后