I am new to iOS app development. I am working on lazy load of images for UICollectionView. The Image are showing but when I scroll the UICollectionView, images change their positions and there are repetition of images where all the images should be unique. Here is my code:
- (MyCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
cell.imageview_collectnvw.layer.cornerRadius=6.0f;
cell.imageview_collectnvw.layer.masksToBounds=YES;
dispatch_queue_t queue = dispatch_queue_create("patientlist",NULL);
dispatch_async(queue, ^{
NSString *str=[[[search_array objectAtIndex:indexPath.row]valueForKey:@"friend"]valueForKey:@"linkedin_photo"];
NSLog(@"cell index path --- is %d",indexPath.row);
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
dispatch_sync(dispatch_get_main_queue(), ^{
if ([[collectionView indexPathsForVisibleItems] containsObject:indexPath]) {
MyCell *cell = (MyCell*)[collectionView cellForItemAtIndexPath:indexPath];
cell.imageview_collectnvw.image=[UIImage imageWithData:data];
}
[cell setNeedsLayout];
NSLog(@"cell index path main is %d",indexPath.row);
});
});
return cell;
}
This may be a silly question but I need the answer.. It will be of great help if anyone can answer this. Thanks in advance.
When working with UICollectionView you should use indexPath.item instead of indexPath.row.
In a UICollectionView or a UITableView, the cells are reused and that's what you are getting at the line where you call dequeueReusableCellWithReuseIdentifier. So, you get an older cell which had images assigned to it to begin with and you are not explicitly setting it to nil before calling the async call, it will still have the older image until the new one is downloaded and set. So, the fix is to assign cell.imageview_collectnvw.image to nil or a placeholder image until the download is successful. Also, manage an array of UIImages that is cached in memory and removed from memory as required for better performance. Check out SDWebImage which does both caching into memory and disk and has got a fantastic performance as far as I have seen. A good start to understand how to setup image loading in a table or UICollectionView is have a look at lazyloading example by Apple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With