【发布时间】:2016-06-22 09:57:48
【问题描述】:
我正在尝试将 URL 中的一些图像显示到我的收藏视图中。但是当我尝试这样做时,我的图像会显示在集合视图上,但它们会随机保持刷新和重新加载。此外,当我尝试滚动 collectionView 时,它会再次重新加载我不想要的整个数据。我只想向用户显示预览图像。 下面是我从 URL 获取图像并将其显示在集合视图上的代码。
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
__block NSString *filename;
for(NSDictionary *item in [jsonSD objectForKey:@"Data"]) {
for (int i=0; i<=[[item objectForKey:@"Count"]integerValue]; i++) {
filename=[NSString stringWithFormat:@"http://..URL../media/content/%@%@%d_1.png",_getstring,[item objectForKey:@"subcategory_id"],i];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:filename];
[self downloadImageWithURL:url completionBlock:^(BOOL succeeded, NSData *data) {
if (succeeded) {
iv.image = [[UIImage alloc] initWithData:data];
}
}];
});
}
}
return cell;
}
- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
completionBlock(YES, data);
} else {
completionBlock(NO, nil);
}
}];
}
这里的“iv”是我的 imageView,我在集合视图的单元格上显示图像。 我尝试搜索相关内容,但我对上述问题没有任何想法。
请帮助我。任何帮助表示赞赏。
【问题讨论】:
标签: ios asynchronous uiimageview uicollectionview nsmutableurlrequest