为了演示如何使用MHLazyTableImages这个类,可以修改苹果官方的LazyTableImages例子项目。现在图片下载的逻辑由MHLazyTableImages和MHImageCache类来处理。TableViewController只做创建一个MHLazyTableImages实例和连接其数据模型与它的表示图。

放置图片到表格单元中:调用addLazyImageForCell:withIndexPath:方法。
这个方法首先会查看是否图片已经存在于缓存中,如果没有则下载之。

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:...];
if (cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:...];

cell.textLabel.text = ...;
[lazyImages addLazyImageForCell:cell withIndexPath:indexPath];
}

当然,你需要告诉MHLazyTableImages关于图片的URL,就发生在一个委托的回调方法中。

- (NSURL*)lazyImageURLForIndexPath:(NSIndexPath*)indexPath
{
AppRecord* appRecord = [self.entries objectAtIndex:indexPath.row];
return [NSURL URLWithString:appRecord.imageURLString];
}

用委托而非直接告诉MHLazyTableImages中单元格应该的URL——是为了适应滚动。当正在滚动时,我们不希望图片还装载。我们将推迟下载,直到用户停止滚动。lazyImageURLForIndexPath:新的可见行会自动调用。

http://www.cnblogs.com/lovecode/archive/2346069.html
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

相关文章: