user7219266
user7219266

Reputation:

iOS - How to properly reload a cell before inserting it dynamically in UICollectionView

I have been facing an understandable behavior while dynamically inserting an object in my datasource.

Here is my code :

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];

[_dataSource insertObject:newObject atIndex:indexPath.row];
[_collectionView insertItemsAtIndexPaths:@[indexPath]];

What I am doing here is inserting an object in my datasource (because this object wasn't ready at launch, and I receive it in a delegate method).

Then, I want to trigger my cellForRow at this specific indexPath in order to create and insert the appropriate cell.

The issue here is that it briefly display the previous content of the cell.

Even though I got this in my custom UICollectionViewCell class :

override func prepareForReuse() {
    super.prepareForReuse()

    self.mediaContainer = nil
    self.outletTitle.text = ""
    self.outletImage.image = nil
    self.outletButtonAction = nil
    self.bottomView = nil
}

Am I using prepareForReuse in a wrong way ?

Should I call reloadItemsAtIndexPath before inserting it ?

Here is my cellForRow :

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Object *object = [_datasource objectAtIndex:indexPath.row];
    UICollectionViewCell *cell = nil;

    switch (object.type.intValue) {

        case CELLTYPE1...  :
        // specific cases for specific cell type

        .
        .
        .
        case CELLTYPE2:
        {
            static BOOL nibMyCellloaded = NO;
                if (!nibMyCellloaded) {
                    UINib *nib = [UINib nibWithNibName:@"CustomCollectionViewCell" bundle:nil];
                    [self.collectionView registerNib:nib forCellWithReuseIdentifier:@"reuseId"];
                }

                CustomCollectionViewCell* customCell = (CustomCollectionViewCell*)[self.collectionView dequeueReusableCellWithReuseIdentifier:@"reuseId" forIndexPath:indexPath];
                [customCell updateCellOutletWith:_customView vc:self];
                 cell = customCell;
            break;



    return cell;
}

Upvotes: 1

Views: 72

Answers (1)

clemens
clemens

Reputation: 17711

You should set outlets to nil in prepareForReuse() because the cell isn't loaded from Storyboard or NIB again. Just reset your contents (e.g. texts, images, control values). You can use the following rule of thumb: Reset only the values in prepareForReuse() which you set in cellForRow().

When your outlets are set to nil then cellForRow() can't assign new values to the views, and thus you will see old values.

Upvotes: 1

Related Questions