我有一个包含 url 作为数组元素的 productImageArray
。
我正在尝试在我的 ImageView 中加载这些 url。
以下是我加载它的方式。
UIActivityIndicatorView *spinner=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.center=CGPointMake(160.0,240.0 );
spinner.hidesWhenStopped=YES;
[self.view addSubview:spinner];
[spinner startAnimating];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];
self.productImage.image = [UIImage imageWithData:storeImageData];
dispatch_sync(dispatch_get_main_queue(), ^{
[spinner stopAnimating];
});
});
问题在于,
- 只有我的 tableview 的最后一个单元格加载图像,而其余单元格不从 url 加载图像
- 是否有任何其他更好的方法可以使用 native 方法将图像从 url 直接加载到我的 UIImage 中?
当我使用以下代码时,我的 tableview 的每个单元格都会加载图像数据,但它仍然会卡住用户界面,直到数据完全加载为止
NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];
self.productImage.image = [UIImage imageWithData:storeImageData];
最佳答案
@Anbu.Karthik 的回答是正确的。
但是,也许最简单的解决方案是使用类似 SDWebImage
的东西,不是吗?这个库将处理这个问题以及更多(缓存、错误管理、适当的 tableview 单元格处理,...)。
我认为您至少应该花几分钟时间看一下:https://github.com/rs/SDWebImage
编辑:
如果您使用 SDWebImage
和 UIActivityIndicator-for-SDWebImage
,您可以将整个代码替换为:
[self.productImage setImageWithURL:[NSURL URLWithString:productImageArray[indexPath.row]]
usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
关于 UIActivityIndicator-for-SDWebImage
的更多信息:https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage
关于ios - 将图像从 Web 服务加载到 UIImage 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37086044/