我有UICollectionView一个自定义的实现UICollectionViewCell.从互联网获取数据阵列,但是当用户访问内容时下载图像.
虽然这可能不是最有效的方式,我不打算以这种方式离开它,它确实暴露了我正在努力解决的某个问题.看起来细胞正在显示"缓存"或"旧"图像,当我慢慢滚动集合视图时,细胞图像不断变化.
这可能是一个问题,实际的细胞图像在那个时刻无法从网上获得,我的问题是如何强制空单元格或某些加载活动监视器而不显示不正确的图像?
提前谢谢,小齿轮
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = @"Event";
EventCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *title = [[events objectAtIndex:indexPath.item] objectForKey:@"title"];
NSString *imageUrl = [[[events objectAtIndex:indexPath.item] objectForKey:@"photo"] objectForKey:@"url"];
dispatch_queue_t imageFetchQ = dispatch_queue_create("image fetched", NULL);
dispatch_async(imageFetchQ, ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
if (imageData)
{
dispatch_async(dispatch_get_main_queue(), ^{
cell.eventImage.image = [UIImage imageWithData:imageData];
cell.eventTitle.text = title;
});
}
});
return cell;
}
Run Code Online (Sandbox Code Playgroud)