Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView repeats cell

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.

like image 549
Rameez Hussain Avatar asked Oct 12 '13 18:10

Rameez Hussain


3 Answers

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;
}
like image 72
eduludi Avatar answered Oct 30 '22 00:10

eduludi


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.

like image 20
user2872882 Avatar answered Oct 30 '22 02:10

user2872882


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! :)

like image 1
Rameez Hussain Avatar answered Oct 30 '22 02:10

Rameez Hussain