I have a UICollectionView
where I display a grid of images downloaded from the Internet. I am using SDWebImage
to load the images. The problem I am facing is that, when I scroll through the UICollectionView
, sometimes the cells repeat themselves, displaying the same image. But when the cell is scroll out of view and then brought back, it has the right image set.
-(UICollectionViewCell*) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
NSString *CellIdentifier = @"Gallery_Cell";
GalleryCell *cell;
if (cell==nil) {
cell= (GalleryCell *)[self.flowCollection dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
ImageItem *dets = [self.imageList objectAtIndex:indexPath.row];
NSURL *mainImageURL = [NSURL URLWithString:dets.smallImageURL];
cell.image.contentMode = UIViewContentModeScaleAspectFill;
cell.image.clipsToBounds = YES;
[cell.image setImageWithURL:mainImageURL placeholderImage:nil];
}
return cell;
}
Has this happened to anyone else? Would highly appreciate any pointers.
On GalleryCell.m
you need to add prepareForReuse
method and there nullify the _image
variable (assuming that you have a image
@property in the cell):
- (void)prepareForReuse {
[super prepareForReuse];
[self setHighlighted:NO];
_image = nil;
}
The following is stated in the "UICollectionView Class Reference":" If you registered a class for the specified identifier and a new cell must be created, this method initializes the cell by calling its initWithFrame: method. For nib-based cells, this method loads the cell object from the provided nib file. If an existing cell was available for reuse, this method calls the cell’s prepareForReuse method instead."
Do you have a prepareForReuse method for your GalleryCell cell class?
you cell class should be a subclass of UICollectionReusableView Class. And check it.
I ended up using “didEndDisplayingCell” method of UICollectionView and ending the current Image download and setting the image to nil. This worked perfectly and there was no more “shuffling” or repetition of images! :)
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