我有tableView,需要从URL加载图片。我有一个包含图像URL的数组,当页面加载时我需要将所有图像加载到tableview中。请注意,不是来自单个URL,而是具有不同URL的数组。我该如何实现呢?请帮忙
感谢。
答案 0 :(得分:34)
您可以使用GCD在后台线程中加载图像,如下所示:
//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *image = [[NSData alloc] initWithContentsOfURL:imageURL];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = [UIImage imageWithData:image];
});
});
您好。但是你可能需要添加一个dispatch_release(concurrentQueue);确保没有泄漏。 - 弗兰克8月25日19:43
答案 1 :(得分:7)
如果您想从互联网下载图片
,可以使用延迟加载- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//All you reusable cell implementation here.
//Since your Images sizes differ. Keep a custom Imageview
if(![imagesForCategories containsObject:indexPath])
{
customImageView.image = [UIImage imageNamed:@"default-image.png"];
NSMutableArray *arr = [[NSArray alloc] initWithObjects:[imageUrlArray objectAtIndex:indexPath.row],indexPath, nil];
[self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];
[arr release];
}
return cell;
}
- (void) loadImageInBackground:(NSArray *)urlAndTagReference
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *imgUrl=[[NSURL alloc] initWithString:[urlAndTagReference objectAtIndex:0]];
NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
UIImage *img = [UIImage imageWithData:imgData];
[imgUrl release];
NSMutableArray *arr = [[NSMutableArray alloc ] initWithObjects:img,[urlAndTagReference objectAtIndex:1], nil ];
[self performSelectorOnMainThread:@selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
[arr release];
[pool release];
}
- (void) assignImageToImageView:(NSMutableArray *)imgAndTagReference
{
[imagesForCategories addObject:[imgAndTagReference objectAtIndex:1]];
UITableViewCell *cell = [celebCategoryTableView cellForRowAtIndexPath:[imgAndTagReference objectAtIndex:1]];
UIImageView *profilePic = (UIImageView *)[cell.contentView viewWithTag:20];
profilePic.image = [imgAndTagReference objectAtIndex:0];
}
答案 2 :(得分:5)
您可以使用SDWebImage,它可以在UITableView中轻松快速地加载图像 https://github.com/rs/SDWebImage
答案 3 :(得分:4)
尝试此代码,imagearray包含图片网址
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [imagearray objectAtIndex:row]]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
cell.imageView.image =image;
return cell;
}
答案 4 :(得分:3)
您需要为延迟加载创建自定义单元格。这将允许您正确下载图像,而不会冻结。这是一个很好的例子,如何做到这一点: Asynch image loading
答案 5 :(得分:-2)
使用afnetworki,太容易了。
//afnetworking
#import "UIImageView+AFNetworking.h"
[cell.iboImageView setImageWithURL:[NSURL URLWithString:server.imagen] placeholderImage:[UIImage imageNamed:@"qhacer_logo.png"]];