我正在将图像加载到tableView,每次功能
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
执行后,会出现不同的图片url..
我的问题是加载图像花费了太多时间..
我的代码是..
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
self.tableView1 = tableView;
static NSString *simpleTableIdentifier = @"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView1 dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.nameLabel.text = title;
NSString *imageURL = [NSString stringWithFormat: @"http://www.xyz.com/image1.png];
cell.thumbnailImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:fullURL]]];
}
return cell;
}
每次图片网址都会改变,加载每个图片都需要时间..
任何人都可以提出任何解决这个问题的想法吗? 多线程如何处理这段代码? 我应该在代码中编辑什么位置?
最佳答案
您必须下载背景图像,例如:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView1 dequeueReusableCellWithIdentifier:simpleTableIdentifier];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSString *u=[NSString stringWithContentsOfFile:r.url encoding:NSUTF8StringEncoding error:nil];
NSURL *imageURL=[NSURL URLWithString:u];
NSData *imageData=[NSData dataWithContentsOfURL:imageURL];
dispatch_sync(dispatch_get_main_queue(), ^{
SimpleTableCell *cell = (SimpleTableCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.thumbnailImageView.image=[UIImage imageWithData:imageData];
[cell setNeedsLayout];
});
});
}
return cell;
}
只需在 TableView 方法中使用上面的代码并进行所需的编辑,这应该适合您。
关于ios - 如何进行多线程以更快地将图像加载到tableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15270395/