iOS延时加载图片

重网上下载图片是很慢的,为了不影响体验,选择延时加载图片是很好的办法。

一个 tableView 列表,左边暂时没有图

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *CellIdentifier = @"myCell";


UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)

{

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle

reuseIdentifier:CellIdentifier] autorelease];

cell.selectionStyle = UITableViewCellSelectionStyleNone;

}



// 设置cell一些数据

AppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];

cell.textLabel.text = appRecord.appName;

cell.detailTextLabel.text = appRecord.artist;

// 如果不存在图片

if (!appRecord.appIcon)

{

if (self.tableView.dragging == NO && self.tableView.decelerating == NO)//不在拖动中和减速时,开始下载图片

{

[self startIconDownload:appRecord forIndexPath:indexPath];

}

//设置图片为空白图片(等待下载)

cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];

}

//如果有图片

else

{

cell.imageView.image = appRecord.appIcon;

}


return cell;

}


关键就是 [self startIconDownload:appRecord forIndexPath:indexPath];

- (void)startIconDownload:(AppRecord *)appRecord forIndexPath:(NSIndexPath *)indexPath

{

IconDownloader *iconDownloader = [imageDownloadsInProgressobjectForKey:indexPath];

if (iconDownloader == nil//已经在下载中的不用重复下载了,没有在下载中就往下走

{

iconDownloader = [[IconDownloader allocinit];

iconDownloader.appRecord = appRecord;

iconDownloader.indexPathInTableView = indexPath;

iconDownloader.delegate = self;

[imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];

[iconDownloader startDownload];

[iconDownloader release];

}

}


IconDownloader  是一个下载图片封装类
关键方法: iconDownloader.delegate = self;
[iconDownloader startDownload];

一个是委托,将来告诉self下载完成更新图片
一个是自己方法开始联网下载图片

委托调用方法,重设图片

- (void)appImageDidLoad:(NSIndexPath *)indexPath

{

IconDownloader *iconDownloader = [imageDownloadsInProgressobjectForKey:indexPath];

if (iconDownloader != nil)

{

UITableViewCell *cell = [self.tableViewcellForRowAtIndexPath:iconDownloader.indexPathInTableView];

cell.imageView.image = iconDownloader.appRecord.appIcon;

}

}


IconDownloader 中的方法

- (void)startDownload

{

self.activeDownload = [NSMutableData data];


NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:

[NSURLRequest requestWithURL:

[NSURL URLWithString:appRecord.imageURLString]] delegate:self];

self.imageConnection = conn;

[conn release];

}


最后 NSURLConnection 的委托需要自己实现了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值